jquery选择器不工作,为什么? [英] jquery selector not working, why?

查看:99
本文介绍了jquery选择器不工作,为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I simply want to manipulate the elements within the #content div, but $('#content') doesn't seem to work, and yet in other places it does! My relevant code is very simple:

<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>



脚本



Script

$(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!
    });
});

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

That is it. If you notice, it does work in some places (the entire click function bound to it is perfectly fine), but where it doesn't work, it strangely does still exist because length = 1. I tried using context as well to search the div, just in case, (using $('#content','body')), but no use.

推荐答案

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

There is a difference between a DOM element and a jQuery selection that contains a DOM element. A jQuery selection is a wrapper around the DOM object to make it easier to use. It doesn't have an id property, but a DOM element does. On the other hand, jQuery does provide a way to access elements' properties using the attr method:

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

然而, length 属性是由jQuery选择提供的,这就是为什么它适用于你。

The length property, however, is provided by a jQuery selection, which is why that works fine for you.

这篇关于jquery选择器不工作,为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆