最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

how to apply click() to a tag using javascript - Stack Overflow

programmeradmin1浏览0评论

I am trying to emulate a click on a basic link that appears like this with no id or class.

<a href="">Click to Start</a>

I have the following code but when i load the page to no click action is performed. What am I doing wrong?

    var a = document.evaluate( '//a[contains(@href, "playnow")]' ,document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null );
    if(a){
        a.click();
    }

I am trying to emulate a click on a basic link that appears like this with no id or class.

<a href="http://www.myebsite.com/service/playnow">Click to Start</a>

I have the following code but when i load the page to no click action is performed. What am I doing wrong?

    var a = document.evaluate( '//a[contains(@href, "playnow")]' ,document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null );
    if(a){
        a.click();
    }
Share Improve this question edited Oct 21, 2011 at 1:18 Dimitre Novatchev 243k27 gold badges303 silver badges436 bronze badges asked Oct 20, 2011 at 15:43 bammabbammab 2,5637 gold badges26 silver badges28 bronze badges 2
  • What browser? Firefox doesn't/didn't have a "click()" method on <a> DOM elements, I don't think. – Pointy Commented Oct 20, 2011 at 15:46
  • Is there a reason why the tag has no ID? Have you verified a in fact has a value (maybe put a window.alert(a); before the click() call to verify) – Mike Christensen Commented Oct 20, 2011 at 15:48
Add a comment  | 

2 Answers 2

Reset to default 10

The easiest way is to add an id to the anchor tag and then invoke the click function on the DOM element

HTML:

<a id="theAnchor" href="http://www.myebsite.com/service/playnow">Click to Start</a>

JavaScript:

document.getElementById('theAnchor').click();

Why your tag doesn't have an ID is strange, but I'll assume for some reason you can't control that. I don't think you can emulate a click through a "click" method, so perhaps try something like:

var a = document.evaluate( '//a[contains(@href, "playnow")]' ,document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null );
if(a){
   window.location.href = a.href;
}
发布评论

评论列表(0)

  1. 暂无评论