开发者

is it possible to set custom attribute by jQuery attr() function using JS variables

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 o开发者_运维问答ther way please suggest Thanks.


I guess you should use this

jQuery('#div').attr(attname,attvalue);


Yes, but use data- prefix before to avoid collision

$('elm').attr('data-'+attname,attvalue);

Using data- prefix doesn't require HTML5.


Yes you can add any attribute you want, just be careful:

$('#foobar').attr('foo','bar'); 

http://jsfiddle.net/each/rnnfk/ - Check out this demo


<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


Square bracket notation is your friend:

var attname = "haha";
jQuery('#div')[0][attname] = "foo";
alert(jQuery('#div')[0][attname]);

http://jsfiddle.net/KJBHq/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜