jQuery:更改加载了 ajax 的元素上的 CSS?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6866043/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery: Changing the CSS on an element loaded with ajax?
提问by qwerty
I need to change the position of an element i'm loading with ajax
. I want to use .css()
to change it but jQuery can't find the element cause it's not being recognized. How do i do to make jQuery "recognize" the element?
我需要更改正在加载的元素的位置ajax
。我想用.css()
它来更改它,但 jQuery 找不到该元素,因为它无法被识别。我该怎么做才能让 jQuery“识别”元素?
I've read about live()
and delegate()
but i can't get neither one of them to work as i want them to. I'd really appreciate some help!
我已经阅读了live()
,delegate()
但我无法让他们中的任何一个都像我希望的那样工作。我真的很感激一些帮助!
回答by Adam Hopkinson
Make the css change in the complete
or success
function of the ajax call. Assuming you're using load
:
在 ajax 调用的complete
orsuccess
函数中进行css 更改。假设您正在使用load
:
$('#el').load(
url,
data,
function(){
$('#selector').css('position', 'absolute');
}
);
Alternatively (and easier to give as an example) register an ajaxComplete
event
或者(更容易举个例子)注册一个ajaxComplete
事件
$(document).ajaxComplete(function(){
if($('#elementID').length != 0) {
$('#elementID').css('position', 'absolute');
}
});
This is fired each time an ajax request completes, checks to see if #elementID exists and if so applies the css.
每次 ajax 请求完成时都会触发它,检查 #elementID 是否存在,如果存在,则应用 css。
回答by ShankarSangoli
If you have to markup in a js variable then you can do it as below.
如果您必须在 js 变量中进行标记,那么您可以按如下方式进行。
$(markup).find("requiredElement").css({ set the properties here });
回答by AlienWebguy
If you want to edit it's CSS, you need to place it in the DOM first, then manipulate it.
如果你想编辑它的 CSS,你需要先把它放在 DOM 中,然后再操作它。
Example:
例子:
$.ajax({
...
success:function(data){
$('<div/>').appendTo('body').html(data).css('border','3px solid red');
}
});