1

这段代码应该说够了:http: //jsfiddle.net/dimadima/fLCCK/3/

// Append and return a newly created `div` element
$el = $('<div id="#test"></div>').appendTo($('body'));

// Now, try to find it:

// Nothing
var attempt1 = $('#test');

// Also nothing
var attempt2 = $('body').find('#test');

// Also nothing
var attempt3 = $('div#test');

// Returns both the pre-existing and dynamically appended divs.
var attempt4 = $('div');

不明白为什么我不能像前 3 次尝试中那样检索这个 div。第四次尝试检索它,但不是令人满意的方式。我觉得我已经成功完成了一百万次。

4

2 回答 2

7

#标志用于引用 div。当你定义它时,你需要省略它:

$el = $('<div id="test"></div>').appendTo($('body'));
于 2013-03-19T04:26:09.647 回答
1

#当你想调用一个对象时应该使用。

$el = $('<div id="test"></div>').appendTo('body');
var length_test = $('#test').length;
console.log(length_test);
//outputs 1
于 2013-03-19T04:52:10.010 回答