如何选择尚不存在的元素(jQuery)并更改其样式?
下面是我的代码。我想更改#preview div 的背景颜色,但它总是无法选择#preview。脚本执行时似乎不存在。其他 jQuery 脚本稍后创建它。
jQuery("#panel").mouseleave(function(){
var good_color = jQuery('.colorpicker_hex input').val();
jQuery("#preview").css({ 'background-color': good_color });
});
如何选择所有当前和未来的 #preview div 并更改其背景颜色?我认为有类似 live() 的东西,但我还没有找到 CSS 更改的示例。
Below is my code. I'd like to change background color of #preview div but it always fails to select #preview. It seems that it doesn't exist when script executes. Other jQuery script creates it later on.
jQuery("#panel").mouseleave(function(){
var good_color = jQuery('.colorpicker_hex input').val();
jQuery("#preview").css({ 'background-color': good_color });
});
How do I select all current and future #preview divs and change their background colors? I think that there's something like live() but I haven't found example with CSS change yet.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
jQuery 没有专门做你所列出的事情。不过,您可以添加一个
style
元素来执行此操作:与所有样式规则一样,该规则将在任何元素与其匹配时应用。当您将其添加到文档元素的末尾时,它应该会赢得任何样式冲突(除非特异性差异,但
id
选择器非常具体)。实例 - 已在 Chrome、Firefox、Opera、IE6 和 IE9 中测试并运行
jQuery doesn't specifically have anything to do what you've listed. You can add a
style
element to do it, though:Like all style rules, that will apply as and when any elements match it. As you're adding it at the end of the document element, it should win any style conflicts (barring specificity differences, but
id
selectors are pretty specific).Live example - Tested and working in Chrome, Firefox, Opera, IE6, and IE9
你不能。基本上 jQuery 通过 DOM 树导航来选择正确的对象。
因此,在加载文档后运行脚本。
您的案例中可能不存在
#panel
或#preview
。You can not. Basically jQuery nevigate via DOM tree to select proper object.
So, run script after document loaded.
#panel
or#preview
might not exist in your case.live()
(现已弃用,因此您应该使用on()
代替)仅适用于事件。无法选择尚不存在的元素。但是,您可以创建这样的元素:并且此 div 尚未附加到您的文档。您可以随意操作它的 CSS:
然后您之前负责创建脚本的脚本可以直接附加它:
live()
(which is now deprecated, so you should useon()
instead) is just for events. There is no way to select an element which doesn't yet exist. However, you can create an element like this:And this div isn't yet attached to your document. You can manipulate its CSS as you please with:
Then your script which was previously responsible for creating the script can just attach it instead: