简体   繁体   中英

Invoking Link in Javascript or jQuery

I have an href taged object (graphic) on a page that I want to programatically click on. However,I can't figure out how to reference the object. Here is the tag:

<div id="getthebutton">
    <div>
        <a onmouseout="MM_swapImage('btn123','','http://www.comp.com/img/btn_img.png',1)" onmousedown="MM_swapImage('btn123','','http://www.comp.com/img/buttons/btn_inv.png',1)" onmouseover="MM_swapImage('btn123','','http://www.comp.com/img/buttons/btn_inv.png',1)" href="javascript:do_activity("param1", 1);">
            <img id="btn123" width="180" height="60" alt="" src="http://www.comp.com/img/buttons/other_btn.png"/>
        </a>
    </div>
</div>

How do I click on this thing? If I read this right "btn123" is just an image file.

To programmatically click on that you would have to do something like this

$("a").click();

Of course it helps to have an event handler assigned first, but it is really that simple :)

Using parentNode will give you access to the <a> tag, but I don't know if that helps you, cause I'm not sure what exactly you are doing.

document.getElementById("btn123").parentNode

I believe in jQuery, it is parent():

$('#btn123').parent()

So you could probably do:

$('#btn123').parent().click()

First off, you should really listen to the comments (javascript: links == dark side). That being said ...

$("div#getthebutton div a").click(); 

In this case, the anchor has a javascript href-value. Understanding that you have no control over the source, your only other option would be to evaluate the value of the HREF:

// run the href-javascript from the parent anchor
eval($("#btn123").parent().attr("href"));

Invoking a click from the code will not invoke the javascript code. As such, you must evaluate it instead.

If you want to get the result of clicking on the image, from the code I would say your JavaScript should simply be:

do_activity("param1", 1);

That's what ultimately happens when the image is clicked by a human. This bypasses the 'click' events, so you might miss out on some side-effects, but it's what I'd try first.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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