简体   繁体   English

HTML 启用 div onclick 中的脚本代码

[英]HTML enable script code within div onclick

I have a div that looks like this:我有一个看起来像这样的 div:

<div id="scriptDiv">
  <script src="URL" id="someId" my-token=""></script>
</div>

I can´t run the script tag within that scriptDiv until I have a token and that token is given when the user presses a button.在我有一个令牌并且当用户按下按钮时给出该令牌之前,我无法在该scriptDiv运行脚本标记。 I can´t render that token until I know that the user want to choose this choice.在我知道用户想要选择此选项之前,我无法呈现该令牌。

So I have a button that renders some JS code when it´s pressed and adds the token to the div with this code:所以我有一个按钮,它在按下时呈现一些 JS 代码,并使用以下代码将令牌添加到 div:

$('#someId').attr('my-token', token);

So the issue is that the scriptDiv is called when the HTML page renders and I get an error.所以问题是当 HTML 页面呈现时调用scriptDiv并且我收到错误。 I only want the scriptDiv to be called when the user has pressed my button.我只希望在用户按下我的按钮时调用scriptDiv

So is it possible to only call the scriptDiv when the button is pressed and not when the page is rendered?那么是否可以只在按下按钮时调用scriptDiv而不是在呈现页面时调用?

If you don't want a script to be executed don't put it in the html or dom until you are ready如果您不想执行脚本,请在准备好之前不要将其放入 html 或 dom 中

<div id="scriptDiv"></div>

Then in your button event create the script element, set it's src to the url, and then append it to the document然后在您的按钮事件中创建脚本元素,将其src设置为 url,然后将其附加到文档

$("#button").click(function(){
   var s = document.createElement("script");
   s.src = "http://www.example.com/jsfile.js";
   s.setAttribute("my-token","whatever your token is"); 
   $("#scriptDiv").append(s);
});

You should set the token attribute of script tag inside the button click event as below.您应该在按钮单击事件中设置脚本标记的令牌属性,如下所示。

$('#buttonId').click(function (){
 $('#someId').attr('my-token', token);
});

I think you're going about this the wrong way.我认为你这样做是错误的。 Look into doing a callback for when you want your code to run and bind that with an event to your button.考虑在您希望代码运行时执行回调并将其与事件绑定到您的按钮。 You can control how that is done in JavaScript.您可以控制在 JavaScript 中的完成方式。 For example, sorry I'm using jQuery here,例如,抱歉我在这里使用 jQuery,

$('#myButton').on('click', function(){
 //your code here
});

This way it will only run when your button is clicked.这样它只会在你的按钮被点击时运行。

You could put the js you want to run in a function eg您可以将要运行的 js 放在一个函数中,例如

function scriptDiv(){
    // Your js here
}

When you want the script to run (when the token is set) just use something that calls the function like:当您希望脚本运行时(设置令牌时)只需使用调用该函数的内容,例如:

<button onclick="scriptDiv()"></button>

You could also check every second if the token is set eg如果设置了令牌,您还可以每秒检查一次

setInterval(function(){if (tokenIsSet) {scriptDiv}},500);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM