jQuery选择器间歇性工作,为什么? [英] jQuery selector intermittent working, why?

查看:64
本文介绍了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>

脚本

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

就是这样.如果您注意到,它确实可以在某些地方使用(绑定到它的整个click函数都很好),但是在不起作用的地方,奇怪的是它仍然存在,因为 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 来访问元素属性的方法.a>方法:

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天全站免登陆