是否可以使用 JS 变量通过 jQuery attr() 函数设置自定义属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7497066/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
is it possible to set custom attribute by jQuery attr() function using JS variables
提问by rain
I'm using jquery 1.5 and html4 standard.
I'm trying to set custom attribute which i get by javascript variable, but it is not setting up.code sample:
我正在使用 jquery 1.5 和 html4 标准。
我正在尝试设置我通过 javascript 变量获得的自定义属性,但它没有设置。代码示例:
var attname="list1"; // this is changed on every call of the function where it is defined.
var attvalue="b,c,d"; // this also changed.
jQuery('#div1').attr({attname:attvalue});
but it treat attname as string itself rather variable. there are other option like using data(),prop() but they are supported in HTML5 and jquery 1.6 that is not possible for me at the moment.other problem is data can't be set on server side to be sync and used at client side by jquery data(). as they are syntactically diff. if there's some other way please suggest Thanks.
但它将 attname 视为字符串本身而不是可变的。还有其他选项,如使用 data(),prop() 但它们在 HTML5 和 jquery 1.6 中受支持,目前对我来说是不可能的。另一个问题是数据无法在服务器端设置为同步和使用客户端通过 jquery data()。因为它们在语法上是不同的。如果有其他方式请建议谢谢。
回答by Sedat Ba?ar
I guess you should use this
我想你应该使用这个
jQuery('#div').attr(attname,attvalue);
回答by Muhammad Usman
Yes, but use data-
prefix before to avoid collision
是的,但data-
之前使用前缀以避免冲突
$('elm').attr('data-'+attname,attvalue);
Using data-
prefix doesn't require HTML5.
使用data-
前缀不需要 HTML5。
回答by daryl
Yes you can add any attribute you want, just be careful:
是的,你可以添加任何你想要的属性,只是要小心:
$('#foobar').attr('foo','bar');
http://jsfiddle.net/each/rnnfk/- Check out this demo
http://jsfiddle.net/each/rnnfk/- 看看这个演示
回答by Andy
<div data-test="lala">asdf</div>
alert($('div').data('test'));
var t = 'data-test2';
var v = 'hiho';
$('div').attr(t,v);
alert($('div').data('test2'));
alert($('div').attr('data-test2'));
this all works for me: http://jsfiddle.net/r7uQ8/Tested on jquery 1.4.4
这一切都对我有用:http: //jsfiddle.net/r7uQ8/在 jquery 1.4.4 上测试
回答by karim79
Square bracket notation is your friend:
方括号表示法是您的朋友:
var attname = "haha";
jQuery('#div')[0][attname] = "foo";
alert(jQuery('#div')[0][attname]);