li属性返回undefined

问题描述:

我的引导页面有一个导航列表,我想在每次点击时获取每个项目的自定义属性的值。我已经尝试了各种各样的方法,但我似乎无法弄清楚为什么该属性一直返回undefined。li属性返回undefined

下面是一些示例HTML:

<ul id="list" class="nav nav-list">    
    <li class=""><a href="#" myval="firstValue">Item 1</a></li> 
    <li class="active"><a href="#" myval="secondValue">Item 2</a></li> 
</ul> 

这里是jQuery的:

$('#list').on('click', 'li:has(a[href^="#"])', function() { 
    var currentVal= $(this).attr('myval'); 
    alert(currentVal); 
}); 

您的自定义属性不上李。你必须从它的孩子获得属性。

var currentVal= $(this).children('a').attr('myval'); 
+0

啊,你说得对!有效!非常感谢:) 如果是我的代码,它会工作如果它是 '

  • Item 1
  • '? – 123321 2013-02-14 01:19:37

    不要使用myval,但data-myval

    <a href="#" data-myval="firstValue"> 
    
    $("#list").on('click', 'li:has(a[href^="#"])', function() { 
        alert($(this).children('a[href^="#"]').data('myval')); 
    }); 
    

    还要注意的是点击的目标是li:has不选择任何内容。您也可以通过删除:has来绑定到a

    +0

    这个作品,谢谢! – 123321 2013-02-14 01:21:16