简体   繁体   English

如何获取Javascript中HTML属性的某些值?

[英]How do I get certain values of a HTML attribute in Javascript?

I would like to take the value of an attribute, process it and then replace a PHP variable with the value we receive at the end. 我想获取一个属性的值,对其进行处理,然后将PHP变量替换为我们最后收到的值。

The data attribute is data-id , all I need assistance with is getting the value of data-id into Javascript on a click event , the rest I can do. data属性是data-id ,我需要帮助的是在click event上将data-id的值获取到Javascript中,剩下的我可以做。

An example: 一个例子:

Person clicks an tag with the data-id set as, say, 7. I'd then need to extract that 7 from the HTML code and into a Javascript variable so I can work with said value. 人员单击数据ID设置为7的标签。然后,我需要从HTML代码中将7提取到Javascript变量中,这样我就可以使用所述值了。

I hope this is clear enough 我希望这足够清楚

This will do the trick. 这将达到目的。

$(selector).click(function(){
    var dataAttrId = $(this).attr('data-id');
    // Your code goes here...
});

Try this 尝试这个

$('#someelement').click(function(){
    $(this).data('id');
});

Use this 用这个

jQuery('your id or class or element').click(function(){
    var mainData= jQuery('your id or class or element').attr('data-id');
alert(mainData);
});

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

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