在A-tag中触发Click Click事件

时间:2012-10-18 06:52:52

标签: javascript jquery events click anchor

  

可能重复:
  Can I call jquery click() to follow an <a> link if I haven’t bound an event handler to it with bind or click already?

我写了以下代码。

<div style="background-color:orange">Click me to open the link
    <br>
    <a target="_blank" href="http://example.com">Link</a>
</div>

<script>
    jQuery('div').click(function(){
        jQuery('a').click();
    });

    jQuery('a').click(function(e){
       alert('It came here!');           
       e.stopPropagation();
       return true;   
    });
</script>

但链接没有打开。

更新:将目标属性添加到A-tag。

3 个答案:

答案 0 :(得分:3)

<div style="background-color:orange">Click me to open the link
    <br>
    <a id="b" href="http://example.com">Link</a>
</div>

jQuery('div').click(function(){
    document.getElementById('b').click();
});

小提琴:http://jsfiddle.net/zZqQs/4/

OR:

jQuery('a')[0].click();

出现jquery click和raw JS click彼此不同。

答案 1 :(得分:1)

首先,您使用的是与您网页上所有 <a>标记相匹配的选择器。也许你想给你的<a> id属性,以便你可以定位一个特定的元素...

<a href="foobar.html" id="foo">foo</a>

您还可以尝试使用trigger函数来模拟元素上的点击 -

$('#foo').trigger('click');

最后要提到的是,您实际上没有调用该方法来打开链接。您可以尝试使用此代码 -

jQuery('a').click(function(e){
   alert('It came here!');
   window.open($(this).attr('href'));    
   return false;   
});

参考 -

  

说明:执行附加到的所有处理程序和行为   给定事件类型的匹配元素。

答案 2 :(得分:1)

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js" type="text/javascript"></script>    
<div style="background-color:orange">Click me to open the link
    <br>
    <a href="http://example.com" target="_blank">Link</a>
</div>

<script>
    $('div').click(function () {
        $('a').click();
    });

    $('a').click(function (e) {

        alert('It came here!');
        e.stopPropagation();
        window.location = $("a").attr("href");
        return true;
    });
</script>
相关问题