繁体   English   中英

如何在点击时按类名从锚标记中获取“id”的属性值?

[英]How to get the attribute value of “id” from the anchor tag by class name when its clicked?

 $("#jqxTree-ReportGroups ul").append("<li id=" + [data[i].Id] + " item-checked='true' item-expanded='true' class='treeLi'> 
<a class='report-tree-expand'  href=''>+</a> 
<a class='reportData' id='12345' href=''>" + [data[i].Name] + "</a></li>");

单击时如何通过类名“reportData”获取“id”的属性值?

编辑:点击不工作..如果我使用Live,该函数被调用...怎么做在实时函数内获取reportData的Id

看看这个代码:

$(document).on('click' , '.reportData' , function(){
   var idProp= $(this).prop('id'); // or attr() 
    var idAttr = $(this).attr('id');
    console.log('using prop = ' + idProp + ' , using attr  = ' + idAttr);
    console.log();
   return false; // to prevent the default action of the link also prevents bubbling 
});

完成使用它已被弃用(需要jquery版本1.7及以上)但这里是使用live()的代码

$('.reportData').live('click' , function(){
   var idProp= $(this).prop('id'); // or attr() 
    var idAttr = $(this).attr('id');
    console.log('using prop = ' + idProp + ' , using attr  = ' + idAttr);
    console.log();
   return false; // to prevent the default action of the link also prevents bubbling 
});

jsfiddle证明工作

http://jsfiddle.net/uvgW4/1/

你可以做

$(document).on("click", ".reportDatan", function() {
    var id = this.id;
});

使用事件委派,因为它看起来像是动态添加它。

尝试这个:

$('.reportDatan').click(function(){
$(this).attr('id');    
});

如果您使用的是jquery 1.9

$('.reportDatan').click(function(){
$(this).prop('id');    
});

你在jQuery中连接HTML字符串是错误的,看看这个具有实时功能的代码,或者如果你想让它可读,你也可以使用JavaScript Template Engine Mustache

HTML:

<div id="jqxTree-ReportGroups">
    <ul>
        <li>First</li>
    </ul>
</div>

jQuery的:

$(document).ready(function () {
   var yourLiID = 100;
   var aValue = 'Report Data';
   var yourLi = "<li id='" + yourLiID + "' item-checked='true' item-expanded='true' class='treeLi'>";
   var yourAnchor = "<a class='report-tree-expand'  href=''>Your Text</a> ";
   var secondAnchor = "<a class='reportData' id='12345' href=''>" + aValue + "</a>";
   var yourLiClose = '</li>';
   $("#jqxTree-ReportGroups ul").append(yourLi + yourAnchor + secondAnchor + yourLiClose);

    $('.reportData').live("click", function(){
      var yourAnchorID = $(this).attr('id');
        alert('yourAnchorID: ' + yourAnchorID);
      return false;
    });

});

请参阅此jsFiddle链接以获取演示

暂无
暂无

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

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