<a id="option1" data-id="10" data-option="21" href="#" onclick="goDoSomething(?,?);">
       Click to do something
</a>

我想要在函数goDoSomething(10, 21)内获得data-iddata-option值,我曾try 使用thisreference:this.data['id'],但它不起作用.

How can I do this?

推荐答案

You can achieve this $(identifier).data('id') using jquery,

    <script type="text/javascript">

        function goDoSomething(identifier){     
            alert("data-id:"+$(identifier).data('id')+", data-option:"+$(identifier).data('option'));               
        }

    </script>

    <a id="option1" 
       data-id="10" 
       data-option="21" 
       href="#" 
       onclick="goDoSomething(this);">
           Click to do something
    </a>

javascript:如果想使用javascript标记,可以使用getAttribute("attributename")

    <script type="text/javascript">

        function goDoSomething(d){
            alert(d.getAttribute("data-id"));
        }

    </script>

    <a id="option1" 
       data-id="10" 
       data-option="21" 
       href="#" 
       onclick="goDoSomething(this);">
           Click to do something
    </a>

Or:

    <script type="text/javascript">

        function goDoSomething(data_id, data_option){       

            alert("data-id:"+data_id+", data-option:"+data_option);
        }

    </script>

    <a id="option1" 
       data-id="10" 
       data-option="21" 
       href="#" 
       onclick="goDoSomething(this.getAttribute('data-id'), this.getAttribute('data-option'));">
           Click to do something
    </a>

Jquery相关问答推荐

如何根据另一个 radio Select 并切换?

什么是不使用 jQuery 的经验技术原因?

具有动态大小图像的马赛克网格 gallery

如何在 JQuery UI 自动完成中使用 source:function()... 和 AJAX

如何在 jQuery 中为 getJSON 设置缓存 false?

禁用 Android 网页中输入焦点的zoom

如何使用 jQuery Select sibling 元素?

jQuery-UI 的自动完成不能很好地显示,z-index 问题

延期与promise

如何使用 Twitter Bootstrap 自动关闭alert

如何使用 jQuery 停止默认链接点击行为

Rails 无法正确解码来自 jQuery 的 JSON(数组变成带有整数键的散列)

jQuery 和 jQuery Mobile 的区别?

如何在 JQuery 中 Select 除单击元素之外的所有类?

如何使用 javascript (jquery) 将整数值添加到返回字符串的值中?

订单对象是否由指定的 jQuery Select 器返回?

更改 div 的内容 - jQuery

在事件中使用 jQuery 获取被点击的元素?

jQuery select2 获取 Select 标签的值?

jQuery:通过 .attr() 添加两个属性;方法