开发者

How do I use a variable value as part of the dom tree?

I understand that I can use eval, but based on what I've read, eval is evil! Are there alternatives I can use?

var key = "foo"; //hardcoded for this example, but should actually be dynamic

console.log(document.myform.foo.value); //prints whatever value its supposed to be

document.myform[key].value = "bar"; //<-- what i wan开发者_运维问答t to do

console.log(document.myform.foo.value); //prints "bar"

Also have jquery. Is this something jquery can make easier to manipulate?


There is nothing wrong with that script. It will work as you expect. Basically, any time you have a . in JavaScript, the value after it can be notated with array notation (which is what you have there)

console.log( window.location === window[ 'location' ] ) // true
var loc = 'location';
console.log( window.location === window[ loc ] ) // true


jQuery is all about accessing the dom tree, if key is an id you can use jQuery like so:

$('#' + key).val();

There are a whole host of selectors to make accessing the dome easy with jQuery (http://api.jquery.com/category/selectors/):

$('input[type="checkbox"]')...
$('input:radio')...

Check-out the selectors link above, its a big part of why jQuery is so nice.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜