简体   繁体   English

jQuery锚链接选择器问题

[英]JQuery anchor link selector issue

I'm trying to select the list anchor link using jquery. 我正在尝试使用jquery选择列表锚链接。 Though 'list' link doesn't exist in the page as shown in the console output, it seems 'click' is still getting triggered. 尽管控制台输出中所示页面中不存在“列表”链接,但似乎仍在触发“点击”。 What could be causing 'list' and 'add' to trigger? 是什么导致“列表”和“添加”触发? I have this simple code using jquery 1.10.2: 我有使用jQuery 1.10.2的以下简单代码:

<!-- <a href="#list">List</a> -->
<a href="#delete">Delete</a>
<a href="#add">Add</a>

<script>
    jQuery(document).ready(function($) {
        if ($('a[href$="#list"]').length>0){
            console.log('list found');
        }else{
            console.log('list not found');
        }

        function opentab(value){
            console.log('opentab: ' + value );
            //perform task here            
        }

        $(document).on('click', 'a[href="#list"]', opentab('list'));
        $(document).on('click', 'a[href="#add"]', opentab('add'));
    });
</script>

console output: 控制台输出:

list not found
opentab: list
opentab: add

Here's jsfiddle link: http://jsfiddle.net/2FHf6/ 这是jsfiddle链接: http : //jsfiddle.net/2FHf6/

you need to declare a function in the event that when this event occurs call this function, currently the method inside event is called on page load as your way of calling is not right: 您需要在发生此事件的情况下声明一个函数,当此事件发生时调用此函数,当前在页面加载时调用event内部的方法,因为您的调用方式不正确:

do like this: 这样做:

$(document).on('click', 'a[href="#list"]', function(){
            opentab('list')
        });
        $(document).on('click', 'a[href="#add"]', function(){
            opentab('add')
        });

UPDATED FIDDLE 更新场

 $(document).on('click', 'a[href="#list"]', function(e){ 
         opentab('list');
 });
 $(document).on('click', 'a[href="#add"]', function(e){
        opentab('add');
 });

Demo: 演示:

http://jsfiddle.net/XJhN6/ http://jsfiddle.net/XJhN6/

See this updated fiddle . 请参阅此更新的小提琴

When you want to call a function on an event triggered and the function needs to pass values, you have to do it in an "wrapper" function, like this: 当您要在触发的事件上调用函数并且该函数需要传递值时,必须在“包装器”函数中进行操作,如下所示:

jQuery(document).ready(function($) {
    if ($('a[href$="#list"]').length>0){
        console.log('list found');
    }else{
        console.log('list not found');
    }

    function opentab(value){
        console.log('opentab: ' + value );
        //perform task here            
    }

    $(document).on('click', 'a[href="#list"]', function() {
        opentab('list');
    });
    $(document).on('click', 'a[href="#add"]', function() {
        opentab('add');
    });
});

Otherwise it will be called when the event listener is set, not on the actual event. 否则,将在设置事件侦听器时而不是在实际事件上调用它。

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

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