【问题标题】:store HTML tag attribute value in a variable using Jquery使用 Jquery 将 HTML 标记属性值存储在变量中
【发布时间】:2012-05-13 02:51:04
【问题描述】:

我正在使用 JQuery 开发应用程序。这是我正在使用的 HTML 代码片段:

<MarkNag class="altcheckboxoff" id="markable_38" Azpimark_id="100038">helburua </MarkNag>    
<MarkNag class="altcheckboxoff" id="markable_2"  Azpimark_id="100002">Oriolek </MarkNag>
<MarkNag class="altcheckboxoff" id="markable_39" Azpimark_id="100039">gas liberalizazioa </MarkNag>

我在 HTML 页面中有下一个 JQuery 脚本:

<script type='text/javascript'>
   $("MarkNag").click(function (){
      $(this).toggleClass("highlight");
   });
</script>

我想知道如果单击此 MarkNag 标记,我如何将“markable_39”存储在变量中。我想我应该使用 .data()。但我真的不知道怎么做。有任何想法吗?谢谢

【问题讨论】:

标签: javascript jquery html


【解决方案1】:

这样做

$("MarkNag").click(function () 
 {
       $(this).toggleClass("highlight");

       var IdOfTag = this.id;
       //or
       IdOfTag = $(this).attr('id');  

 });

【讨论】:

    【解决方案2】:

    另外,你可以使用this.id, 喜欢:

    var id = this.id;
    

    【讨论】:

    • 没错,而且更简单。很好的答案。
    【解决方案3】:

    实际上,正确的代码应该是$(this).attr("id")

    【讨论】:

    • 是的,我知道,只是习惯将其包装在 $(this) 中。我在上面评论了 nymous 的回答。
    【解决方案4】:
    $("MarkNag").click(function (){
       $(this).toggleClass("highlight");
    
       alert(this.id);               // Method 1: this.id
       alert($(this).attr('id'));    // Method 2: $(this).attr('id')
    });
    

    【讨论】:

      【解决方案5】:

      在这里你会从事件发生的地方得到对象

      var eventobject = arguments.callee.caller.arguments[0];
      

      您可以在此处访问 currentTarget 的任何属性(在本例中为 id)

      var id = $(eventobject.currentTarget).attr("id");
      

      【讨论】:

        猜你喜欢
        • 2013-11-13
        • 1970-01-01
        • 2016-04-08
        • 1970-01-01
        • 2017-12-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-03-28
        相关资源
        最近更新 更多