1

I've read a billion questions like this, but never found an answer yet.

Anyway, when I type

var variableContainingID = "header";
var div = $("#"+variableContainingID);

It returns 'undefined'

But when I type

var variableContainingID = "header";
var div = $('[id^="'+variableContainingID+'"]');

It works fine. Any ideas why?

UPDATE

var json = '{"divs":['
var children = $(".parent_container > div");
var idArray = [];
var numArray = [];
for (var x=0; x<children.length; x++) {
    var eleid = $(children[x]).attr("id");
    idArray.push('"'+eleid+'"');
    numArray.push(x+1);
}
var idString = idArray.join(",");
var numString = numArray.join(",");
json += idString;
json += '],"number":['+numString+']}';
var obj = JSON.parse(json);
for (x in obj["divs"]) {
    var div = $('[id^="'+obj["divs"][x]+'"]');
}

Do you think the double quotes could be throwing it off?

4

1 回答 1

4

正如您在问题中所写:

var div = $("#"+variableContainingID);
var div = $('[id^="'+variableContainingID+'"]');

这两行并不完全相同。第一个,将选择一个带有idof的元素headerid第二个,选择具有以给定字符串 ( ) 开头的值指定的元素header

因此,如果您有这样的元素:

<div id="headerHere"></div>

第一个 ( $("#"+variableContainingID)) 不能选择它,但第二个 ( $('[id^="'+variableContainingID+'"]')) 可以选择该元素。 这是因为您^=在选择器中使用了。请参阅 jQuery API:属性以选择器开头 (name^="value")

值得一看attributejQuery 中的所有选择器。

于 2013-05-11T08:17:04.710 回答