点击()不使用链接

问题描述:

我有一个页面,其中有几个链接,都是这样的:

I have a page with a few links that are all like this:

<a href="/" class="answer-item" rel="0">10</a>

我想使用click()函数来模拟用户点击其中一个,它在我的测试中似乎不工作。

I would like to use the click() function to simulate a user's click on one of them, but it doesn't seem to work in my tests.

//Evaluate a mathematical expression from another part of the page
var numberAnswer = eval(document.getElementById("question-title").getElementsByTagName("b")[0].innerHTML);

//Builds an array with the links that may match the expression
var choices = document.getElementsByClassName('answer-item');

//Iterates through array to find a match then clicks it
for(var i in choices){
    if(choices[i].innerHTML == numberAnswer){
        choices[i].click();
        break;
    }
}

我确定选项[i] 是正确的元素。

Firefox不执行任何操作,Opera不执行任何操作,

Firefox does nothing, Opera does nothing, and click() is not available in Chrome (I think).

此外,我已尝试在此表单中使用 dispatchEvent()

Also, I have tried to use dispatchEvent() in this form:

var evt = document.createEvent('MouseEvents');
evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
choices[i].dispatchEvent(evt);

这显然在Firefox和Chrome中返回了 true 但是没有改变任何东西。

This apparently returned true in Firefox and Chrome but did not change anything.

最麻烦的部分是只有 href 属性的链接工作正常 .click()

The most bothersome part is that a link with only the href attribute works fine with .click().

>

EDIT

根据评论区域中的讨论,似乎此答案中使用的行为是非标准的,或者至少在用户代理之间不一致。我正在进一步研究这个问题;如果您使用此答案中的信息,请仔细检查所有浏览器中的代码,以确保其正常工作。

Per discussion in the comment area, it seems that the behavior used in this answer is non-standard, or at least not consistent across user-agents. I am researching this issue further; if you use the information in this answer, please carefully check your code in all browsers to ensure it works as expected.

编辑2

根据OP的评论,有一个只是让它发生的方法,在这里工作。它有一些缺点,即你的绑定事件不能调用 preventDefault - 这个方法不会尊重它。你可以建立某种类型的事件封装器,可能能够处理这个...无论如何,这里的代码和小提琴:

Per the comment from the OP, there is a "just make it happen" approach that would work here. It has some downsides, namely that your bound events cannot call preventDefault -- this method will not respect it. You could build some kind of event wrapper that might be able to deal with this... anyway, here's the code and fiddle:

HTML:

<br><br>
<!-- I am totally misusing this API! -->
<a href="http://jsfiddle.net/echo/js/?delay=0&js=The link was followed;" id="progra_link">Some link with an event that uses preventDefault()</a>
<br><br>
<button id="doit_btn">Programmatically click the link</button>

脚本:

function do_program_click () {
    var lnk = document.getElementById('progra_link');
    var loc = lnk.href;
    if (!loc)
        return false;            
    // call this to fire events
    lnk.click();

    // then follow the link
    document.location = loc;
    return;
};
function addEvent(element, evnt, funct){
  if (element.attachEvent)
   return element.attachEvent('on'+evnt, funct);
  else
   return element.addEventListener(evnt, funct, false);
}

// bind an event to the link to test force event trigger
addEvent(
    document.getElementById('progra_link'),
    'click',
    function (e) {
        e.preventDefault();
        alert('Testing element click event, default action should have been stopped');
        return false;
    }
);
// bind event to the leeroy button
addEvent(
    document.getElementById('doit_btn'),
    'click',
    do_program_click
);

jsFiddle: http://jsfiddle.net/CHMLh/

jsFiddle: http://jsfiddle.net/CHMLh/

strong>

Original answer

您的示例代码不完整。如果我只是基础,它工作正常:

Your sample code is incomplete. If I take just the basics, it works correctly:

<script>
   var lnk = document.getElementById('test');
   lnk.click();
</script>
<a id="test" href="/" class="answer-item" rel="0">test link</a>

jsFiddle: http://jsfiddle.net/cgejS/

jsFiddle: http://jsfiddle.net/cgejS/

我会重新评估你处理正确的dom元素的假设。

I would re-evaluate your assumptions that you're dealing with the correct dom element.

在不相关的备注上,这是:

On an unrelated note, this:

var numberAnswer = eval(document.getElementById("question-title").getElementsByTagName("b")[0].innerHTML);

...什么? eval 是邪恶的 - 如果你因任何原因使用它,问你是否有正确的方法。你试图从字符串中获取一个整数?请参阅 parseInt docs ),这个工作的正确工具:

... what? eval is evil -- if you're ever using it for any reason, question whether you have the right approach. Are you trying to get an integer out of a string? See parseInt (docs), the right tool for this job:

// this line is still failure-prone...
var ele = document.getElementById("question-title").getElementsByTagName("b")[0];
var numberAnswer = 0;
if (ele)
   numberAnswer = parseInt(ele.innerHTML);