简体   繁体   English

单击javascript中的锚标记可在控制台中使用

[英]Click on anchor tag in javascript works on in console

I have few anchor tag like following 我有几个像这样的锚标签

<a href="#" id="anchor tag id" class="pointer-level">Button</a>

After page loads, the all anchor tag which has id of " GTid_3 " should be triggered (click event). 页面加载后,应触发所有ID为“ GTid_3 ”的锚标记(点击事件)。 I wrote a jquery code 我写了一个jQuery代码

<script>

    $(document).ready(function(){
    })

    $('.pointer-level').each(function(){    
        if($(this).attr("id")=="GTid_3")    
            $(this).click()
    })
</script>

This does not work if I included within <script></script> tag. 如果我包含在<script></script>标记中,则此方法不起作用。 But if I paste it in console (developer option), its working fine. 但是,如果我将其粘贴到控制台 (开发人员选项)中,则可以正常工作。 This makes me mad. 这让我生气。 I couldnot understand why it does not when included in the page. 我不明白为什么页面中没有它。 Is there any event called when we work in console? 在控制台中工作时是否会调用任何事件?

It seems that you're running your code before the elements are being created. 似乎在创建元素之前正在运行代码。 You can also easily debug it with console.log s, like so: 您也可以使用console.log轻松调试它,如下所示:

$(document).ready(function(){
    $('.pointer-level').each(function(){    
         console.log('.pointer-level found');
        if($(this).attr("id")=="GTid_3") {
            console.log('#GTid3 found!');
            $(this).click()
        }
    })
})

You didn't mention where exactly you are putting that <script> , but if the same code exactly works through the console, it also needs to work in action. 您没有提到<script>确切位置,但是如果相同的代码在控制台中完全可以正常工作,那么它也需要实际起作用。

Try to use $(document).find('.pointer-level').each(function() if your ids adding dynamically. And for triggering click use $(this).trigger('click') 如果您的ID是动态添加的,请尝试使用$(document).find('.pointer-level').each(function() 。要触发点击,请使用$(this).trigger('click')

Stack Snippet 堆栈片段

 $(document).ready(function() { $(document).find('.pointer-level').each(function() { if ($(this).attr("id") == "GTid_3") $(this).trigger('click'); }); }) $(document).on('click', '#GTid_3', function() { console.log('clicked '+$(this).text()); }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a class="pointer-level" id="GTid_3">1</a> <a class="pointer-level">2</a> <a class="pointer-level" id="GTid_3">3</a> <a class="pointer-level">4</a> <a class="pointer-level" id="GTid_3">5</a> 

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

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