jquery选择器不工作,为什么?

use*_*627 3 html jquery javascript-events selector

我只是想操纵#content div中的元素,但$('#content')似乎不起作用,但在其他地方却有效!我的相关代码非常简单:

HTML

<body>
  <input type='button' value='Save design' id='save'  />
  <div id="content" style="height: 200px; width:600px;border: 1px solid black;" class='whatev'></div>
</body>
Run Code Online (Sandbox Code Playgroud)

脚本

$(document).ready(function(){   
   $('#save').click(function(e){
     alert( document.getElementById('content').id); // this works!
     alert($("#content").length); // this works! it outputs "1"
     alert($("#content").id); // this does NOT work - undefined, why?
     //end save function
   });

    $('#content').click(function(e){ 
       // do stuff // ALL of this works!
    });
});
Run Code Online (Sandbox Code Playgroud)

这就对了.如果你注意到,它确实在某些地方有效(整个点击功能完全正常),但是如果它不起作用,它奇怪地仍然存在,因为length = 1.我尝试使用上下文来搜索div,以防万一,(使用$('#content','body')),但没有用.

lon*_*day 12

DOM元素和包含DOM元素的jQuery选择之间存在差异.jQuery选择是DOM对象的包装,使其更易于使用.它没有id属性,但DOM元素有.另一方面,jQuery提供了一种使用该attr方法访问元素属性的方法:

document.getElementById('content').id // access the id property of a DOM element
$('#content').attr('id')              // use jQuery to select the element and access the property
Run Code Online (Sandbox Code Playgroud)

length但是,该属性由jQuery选择提供,这就是为什么它适用于您.


ade*_*neo 9

id 是一个普通的DOM属性/属性,它使用普通的DOM对象,而不是jQuery对象.

你会在jQuery中这样做:

$("#content").attr('id');
Run Code Online (Sandbox Code Playgroud)

等于:

document.getElementById('content').id
Run Code Online (Sandbox Code Playgroud)

要么

$("#content")[0].id; //[0] gets the first DOM object in the collection
Run Code Online (Sandbox Code Playgroud)