简体   繁体   English

触发单击事件以使用 jquery 在 href 上动态添加链接

[英]Trigger click event to dynamically added link on href using jquery

I am dynamically creating the link on anchor tag through jquery, I want to trigger click event as soon as link gets attached to href , but in my case click event didn't get triggered.我正在通过 jquery 在锚标记上动态创建链接,我想在链接附加到href立即触发点击事件,但在我的情况下,点击事件没有被触发。

JQuery :查询

$("#refShare").click(function(e){
    jQuery.ajax({
        url: base_url+"create-refer",
        cache : false,
        dataType: 'json',
        data: { email:email },  
        type:'post',
        success:function(response){
            jQuery('li#refShare a:first').attr("href", 'https://www.xyzLink.com/'+response.link);
            jQuery('li#refShare a:first').attr("target", 'blank');
            jQuery('li#refShare a:first').click();
       }); 
});

HTML : HTML :

<ul>
<li id="refShare">
<a href="" id="share-facebook">
<i class="fa fa-facebook fa-2x" aria-hidden="true"></i>
</a>
</li>
<li>
    ....
</li>
    .....
</ul>

尝试触发

$("#refShare").trigger("click")

You need to choose the right element which can be clickable and your goal to redirect to somewhere else automatically(where human intervention does not require) can be achieved by using 'trigger' function.您需要选择可以点击的正确元素,并且可以通过使用“触发”功能来实现自动重定向到其他地方(不需要人工干预)的目标。

you can do :你可以做 :

$('#share-facebook').trigger('click');

For further details/documentation about jquery 'trigger' function, you can check this url: .trigger()有关 jquery 'trigger' 功能的更多详细信息/文档,您可以查看此网址: .trigger()

Do you want an auto click or manual click?你想要自动点击还是手动点击?

If you want an auto => jQuery('li#refShare a:first').trigger( "click" );如果你想要一个 auto => jQuery('li#refShare a:first').trigger( "click" ); Otherwise manually means assign one id to this href and make it click.否则手动意味着为这个 href 分配一个 id 并让它点击。 jQuery('li#refShare a:first').attr("id", 'some_id'); jQuery('li#refShare a:first').attr("id", 'some_id');

outside Ajax阿贾克斯外

  jQuery('#some_id').on('click','#some_id', function() {
    //do it your stuff...
 });

Try this尝试这个

 jQuery(document).ready(function(){ setTimeout(function(){ alert("Hello"); jQuery('#Link_xyz').attr("href", 'https://github.com/gauravin213'); jQuery('#Link_xyz').attr("target", 'blank'); jQuery('#Link_xyz').click(); }, 3000); jQuery(document).on('click', '#Link_xyz', function(){ var target = jQuery(this); var url = target.attr('href'); alert("click: "+url); //window.open(url, '_blank'); window.location.href = url; }); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div> <a id="Link_xyz" href="">Link</a> </div>

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

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