简体   繁体   English

Javascript:单击注入按钮?

[英]Javascript: Click on an injected button?

My question may seem weird but I'd like my javascript code to click on a button I previously injected in the page with the same script. 我的问题似乎很奇怪,但我希望我的javascript代码单击我以前在页面中注入的具有相同脚本的按钮。 I tried something like this: 我尝试过这样的事情:

var injectionarea = document.getElementById('whereIwant');
injectionarea.innerHTML += "<button id=\"my_button\">Test</button>";

document.getElementById('my_button').onclick = function() {
                                                            //my stuff
                                                          };

my_button.click();

But it returns an undefined element... 但是它返回一个未定义的元素...

There are some issues in what you're trying to do. 您尝试执行的操作中存在一些问题。 As a general rule, injecting a dom control as a string can give some weird happenings (eg. any child node in the container element may revert to original page state). 通常,将dom控件作为字符串注入会带来一些奇怪的情况(例如,容器元素中的任何子节点都可能恢复为原始页面状态)。 So it's better to create the object by document.createElement function. 因此最好通过document.createElement函数创建对象。

Anyway, in your case, you simply need to "wait" that the dom reads your injection, parse it and create the element (things that you should done yourself, as stated above). 无论如何,在您的情况下,您只需要“等待” dom读取您的注射剂,解析它并创建元素(如上所述,您应该自己做的事情)。

So, adding a setTimeout, like in the following example, would make it work, even if it's not the cleanest piece of code I would like to see: 因此,添加setTimeout就像下面的示例一样,即使它不是我希望看到的最干净的代码,也可以使它工作:

var injectionarea = document.getElementById('whereIwant');
injectionarea.innerHTML += "<button id=\"my_button\">Test</button>";

setTimeout(function(){
   document.getElementById('my_button').onclick = function() {
                                                            //my stuff
                                                          };

   my_button.click();
},0);

Always remember that JS is single threaded, so any edit you make that need to be parsed by the DOM, would not be available in the DOM itself until you release your working thread. 永远记住,JS是单线程的,因此您需要由DOM解析的任何编辑都不会在DOM本身中可用,直到您释放工作线程。

try this: 尝试这个:

function a(){
    var injectionarea = document.getElementById('whereIwant');
    injectionarea.innerHTML += "<button id=\"my_button\" onclick=\"doClick()\">Test</button>";
}
function doClick(){
//my stuff
}

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

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