javascript - JQuery 根据值设置自定义属性

标签 javascript jquery html

假设这段代码:

<input id="myinpunt-name"  my_attribute="1"  class="myclass" ...
<checkbox id="myinpunt-name"  my_attribute="2"  class="myclass" ... 



$('.myclass').change(function() {
        dosomething($(this).attr('my_attribute'));
 });

并且工作正常。

现在我还有另一个组件

<select id="myselect-name" my_attribute = /* here I want to read Value*/ class="myclass"  ...

在这种情况下,my_attribute 必须读取 $(this).val()

有办法将 value 属性设置为自定义属性吗?

谢谢。

最佳答案

无论哪种方式(内联或单独),您都需要根据下拉列表的更改事件设置/更改 custom_attribute 的值,如下所示:

内联:

<select id="myselect-name" my_attribute="1"
    onchange="javascript: this.setAttribute('my_attribute', this.value);">
    <option>1</option>
    <option>2</option>
    <option>3</option>
</select>

DEMO - 1

单独:

<select id="myselect-name" my_attribute="1" class="myclass">
    <option>1</option>
    <option>2</option>
    <option>3</option>
</select>

$('.myclass').change(function() {
    $(this).attr('my_attribute', $(this).val());
    alert($(this).attr('my_attribute'));
});

DEMO - 2

关于javascript - JQuery 根据值设置自定义属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33732997/

相关文章:

javascript - For 循环和追加

javascript - 在 javascript 和 html 中转义撇号(单引号)字符

javascript - 如何通过javascript检查浏览器的在线/离线状态?

javascript - Jquery - .click() 不滚动页面

node.js - 包含 JSON 文件作为 Webpack 输出,但不属于 bundle.js

html - 重新处理 ie7 中的 block 内容

javascript - 当到达数据对象末尾时停止迭代

jquery - Flexslider 2 垂直缩略图导航

javascript - <form> 外部提交按钮中带有 "formnovalidate"的 jQuery 验证

jquery - 如何正确使用 fullpage.js 的 onLeave() 函数?