首页 > 解决方案 > HTML / JS - 从 index.js onclick 调用函数

问题描述

我想在我的 index.js 中调用一个函数,在我的 features.js 中,但是因为它链接到我不能使用 import 或 require 的浏览器?

我有一个 index.js、index.html 和另一个 features.js 文件。

功能.js 文件由 index.html 使用,在这个文件中,我在特定情况下附加了一些 html,我想做的是 onclick 调用一个函数,但从我的 index.js 文件中调用这个函数,它必须在那里,因为它需要一个socket.id。

看这里:

*功能.js:

$('#messages').append($('<li id="messageclient">').append($(`
        <div id="message-cont" class="message-cont">     
        <div class="orderDetailsWrapper">
        <div class="detailsHeaderWrapper">
            <div class="orderNum"></div>
            <div class="customerName"></div>
        </div>

        <div class="textToCustomer">
        <p> Please click on the item you want to return</p>

       </div>

        <div class="itemBoxWrapper">
            <div class="item1Wrapper" onclick="matchingResponse()">
                <div class="item1Title"></div>
                <div class="item1Price"></div>
            </div>

*index.js

function matchingResponse() {
    var options = {
        method: 'POST',
        uri: 'https://dialogflow.googleapis.com/v2beta1/projects/returnsbot-50668/agent/sessions/1:detectIntent',
        headers: {
            'Authorization': `Bearer ${oAuthToken}`,
            'Content-Type': 'application/json'
        },
        body: {
            "queryInput": {
                "event": {
                    "name": "Matching",
                    "languageCode": "en"
                }
            }
        },
        json: true // Automatically stringifies the body to JSON
    };
    // initial message triggering.
    rp(options)
        .then(function (parsedBody) {
            console.log('DF response' + JSON.stringify(parsedBody))
            console.log('text ^^^^^^^^^^^^^^ ' + JSON.stringify(parsedBody.queryResul))
            text = parsedBody.queryResult.fulfillmentText;

            response = text;
            console.log('matching response +++++++++++' + text);

            data = [details.chatuser, response]
            io.of('/main').to(socket.id).emit('response', data);

        })
        .catch(function (err) {
            console.log(err);
        });
}

因为 socket 函数在 index.js 文件中,所以我需要它里面的这个匹配响应函数来使用适当的 ID。

麻烦在于function.js 我不能使用import / require。

我能做些什么?

标签: javascripthtmlsockets

解决方案


如果您没有在加载时调用任何函数,只需将 features.js 和 index.js 文件添加到您的 html 中。


推荐阅读