问题
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:
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.
回答1:
I guess you should use this
jQuery('#div').attr(attname,attvalue);
回答2:
Yes, but use data-
prefix before to avoid collision
$('elm').attr('data-'+attname,attvalue);
Using data-
prefix doesn't require HTML5.
回答3:
Yes you can add any attribute you want, just be careful:
$('#foobar').attr('foo','bar');
http://jsfiddle.net/each/rnnfk/ - Check out this demo
回答4:
<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
回答5:
Square bracket notation is your friend:
var attname = "haha";
jQuery('#div')[0][attname] = "foo";
alert(jQuery('#div')[0][attname]);
http://jsfiddle.net/KJBHq/
来源:https://stackoverflow.com/questions/7497066/is-it-possible-to-set-custom-attribute-by-jquery-attr-function-using-js-variab