【问题标题】:How to access data attributes of anchor tag in Jquery?如何在 Jquery 中访问锚标记的数据属性?
【发布时间】:2016-08-29 19:26:07
【问题描述】:

案例1:使用锚元素的'onclick'属性调用的函数

<a href='#' onclick='modifyCustomerDetails()' data-action='modifyCustAction' data-params='customerId=567'>Modify Customer</a>

function modifyCustomerDetails() {
    var srcEl = $(this); 
    console.log("ACTION::"+srcEl.data('action')) ;  
    console.log("PARAMS::"+srcEl.data('params')) ;          
}

浏览器控制台中的输出是
未定义
未定义

案例 2: 使用 jquery 绑定锚元素

$('a').bind('click', function() {

  var srcEl = $(this); 
  console.log("ACTION::"+srcEl.data('action')) ;    
  console.log("PARAMS::"+srcEl.data('params')) ;    
})

浏览器控制台中的输出
modifyCustAction
客户 ID=567

我读到 jQuery 将回调函数的范围设置为作为回调主题的元素。

  1. 为什么在案例 1 & 中数据属性不可访问/未定义 只能在案例 2 中访问?
  2. 案例1如何访问锚元素的数据属性?

【问题讨论】:

    标签: jquery html5-data


    【解决方案1】:

    id= "modify_customer" 添加到您的锚标记

    并使用这个 jquery 代码

    <a href="#" onclick="modifyCustomerDetails()" 
    data-action="modifyCustAction" 
    data-params="customerId=567" 
    id="modify_customer"> Modify Customer</a>
    
    $(function(){ 
    var a = $("#modify_customer").data('params')
    alert(a)
    });
    

    它会给出结果customerId=567

    【讨论】:

      【解决方案2】:

      我没有清楚地理解你的问题,但我认为你想要这个

      $('a').click(function(){
      var propty= $(this); 
      var action =propty.attr("data-action");
      });
      

      【讨论】:

        【解决方案3】:

        案例 1:

        <a href='#' onclick='modifyCustomerDetails(this)' data-action='modifyCustAction' data-params='customerId=567'>Modify Customer</a>
        
        function modifyCustomerDetails(obj) {
            console.log("ACTION::"+$(obj).attr('data-action')) ;  
            console.log("PARAMS::"+$(obj).attr('data-params')) ;          
        }
        

        【讨论】:

          【解决方案4】:

          案例1在函数内部传递this

          <a href='#' onclick='modifyCustomerDetails(this)' 
          data-action='modifyCustAction' data-params='customerId=567'>Modify Customer</a>
          
          function modifyCustomerDetails(currObj) {
              var srcEl = $(currObj); 
              console.log("ACTION::"+srcEl.data('action')) ;  
              console.log("PARAMS::"+srcEl.data('params')) ;          
          }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2018-08-25
            • 2011-12-28
            • 2014-05-02
            • 2015-05-09
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多