jQuery 将 $(this) 存储在变量中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10432228/
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
Storing $(this) in a variable
提问by ilyo
If I want to save this
as a jQuery DOM object and then select it, which method below should I use?
如果我想保存this
为jQuery DOM对象然后选择它,我应该使用下面的哪种方法?
var element = $(this)
And then for selecting
然后选择
$(element)
Or simply
或者干脆
var element = this
Also, if I want then to concatenate element
into a larger selector, is this:
另外,如果我想然后连接element
成一个更大的选择器,是这样的:
$(element + " .class")
the right way?
正确的方式?
回答by gabitzish
var element = $(this)
Then you can use element
instead of $(this)
. You don't have to insert element
into $()
anymore.
然后你可以使用element
代替$(this)
。您不必插入element
到$()
了。
For example : element.remove()
instead of $(this).remove()
例如:element.remove()
代替$(this).remove()
回答by CambridgeMike
$this = $(this)
is usually what people do. The dollar sign is a valid character for a variable name, so it serves as a good reminder that the variable is a jQuery object.
$this = $(this)
通常是人们所做的。美元符号是变量名的有效字符,因此它可以很好地提醒变量是 jQuery 对象。
You can then use $this
as you would any jQuery element. For example, $this.css('border', 'none')
然后,您可以$this
像使用任何 jQuery 元素一样使用。例如,$this.css('border', 'none')
回答by TheUnexpected
var element = $(this)
for storing
var element = $(this)
用于存放
then element
for selecting
然后element
选择
回答by OlliM
If you want to select all items with class myClass, you should do:
如果要选择类 myClass 的所有项目,则应执行以下操作:
var $this = $(this);
var myClassElements = $(".myClass", $this);
回答by user7731358
The right way is:
正确的方法是:
var element= this.html();
$(element).find(div) /* from modefy div you can change it with any other selector */
$(element).attr({"class":"myClass","other atrribut":"it's value"});
I hope that is useful.
我希望这是有用的。