Javascript 获取html元素的onclick事件的data-*属性
我想在函数Javascript 获取html元素的onclick事件的data-*属性,javascript,jquery,html,Javascript,Jquery,Html,我想在函数godomething(10,21)中获取data id和data选项值我曾尝试使用this参考:this.data['id'],但它不起作用 我该怎么做?像这样: <a id="option1" data-id="10" data-option="21" href="#" onclick="goDoSomething(?,?);"> Click to do something </a> 工作示例:您可以使用jquery实现此$(标识符).dat
godomething(10,21)
中获取data id
和data选项
值我曾尝试使用this
参考:this.data['id']
,但它不起作用
我该怎么做?像这样:
<a id="option1" data-id="10" data-option="21" href="#" onclick="goDoSomething(?,?);">
Click to do something
</a>
工作示例:您可以使用jquery实现此
$(标识符).data('id')
$(this).data('id');
$(this).data('option');
或:
函数goDoSomething(数据标识,数据选项){
警报(“数据id:+数据id+”,数据选项:+数据选项);
}
以下是一个示例
<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>
$('.facultyselector')。单击(函数(){
var unhide=$(此).data(“教员”);
});
这会将var unhide设置为ahs,因此使用.data(“foo”)获取要获取的data-*属性的“foo”值用户$()
从链接获取jQuery
对象,并使用数据()
获取值
<a class="facultySelecter" data-faculty="ahs" href="#">Arts and Human Sciences</a></li>
$('.facultySelecter').click(function() {
var unhide = $(this).data("faculty");
});
我只是简单地使用jQuery技巧:
<a id="option1"
data-id="10"
data-option="21"
href="#"
onclick="goDoSomething($(this).data('id'),$(this).data('option'));">
Click to do something
</a>
它获取聚焦的
a
元素,并从中获取数据id
属性。检查数据属性是否存在,然后执行操作
$("a:focus").attr('data-id');
函数get_attribute(){alert($(this).attr(“数据id”);}
阅读更多
作者在标记“jQuery”时,建议您使用$(identifier.data('id');)编写方法感谢Maxime Lorant,还添加了
Jquery
选项。我宁愿$('.facultyselector')。在(“单击”,function(){var unhide=$(this.data(“教员”);})代码>下面是一个使用vanilla JS的答案
<a id="option1"
data-id="10"
data-option="21"
href="#"
onclick="goDoSomething($(this).data('id'),$(this).data('option'));">
Click to do something
</a>
$("a:focus").attr('data-id');
$('body').on('click', '.CLICK_BUTTON_CLASS', function (e) {
if(e.target.getAttribute('data-title')) {
var careerTitle = $(this).attr('data-title');
if (careerTitle.length > 0) $('.careerFormTitle').text(careerTitle);
}
});