Javascript 将 JQuery DOM 元素保存为变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6741015/
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
Saving a JQuery DOM element as a variable
提问by egidra
I am trying to store a DOM element into a variable by using this code:
我正在尝试使用以下代码将 DOM 元素存储到变量中:
var save_status = $(this).siblings(".save-status")[0];
save_status.append("<img src="images/loading-small.gif" width=30 />");
I get the following error though:
虽然我收到以下错误:
Uncaught SyntaxError: Unexpected identifier
Any idea why I might be getting this error? Thanks!
知道为什么我可能会收到此错误吗?谢谢!
回答by citizen conn
Replace
代替
save_status.append("<img src="images/loading-small.gif" width=30 />");
with
和
save_status.append('<img src="images/loading-small.gif" width=30 />');
The problem is in your quotations.
问题出在你的报价单上。
回答by jkoreska
You're getting the error because your quotes are not escaped (or literal).
您收到错误是因为您的引号没有转义(或文字)。
To answer your other question (per the title and example), you can save a jQuery object, or a DOM element, but they're not the same. For example:
要回答您的其他问题(根据标题和示例),您可以保存jQuery object或DOM element,但它们不一样。例如:
var x = $(selector); // returns jQuery object
var y = $(selector)[0]; // returns DOM element
x.append('stuff'); // use jQuery functions directly
$(y).append('stuff'); // pass the DOM element to jQuery first
回答by Alfonso Rubalcava
I see several things. Try this example:
我看到了几件事。试试这个例子:
<style>
#mydiv{
display: block;
width: 100px;
height: 100px;
background-color: red;
}
</style>
<script src="../assets/js/jquery-1.6.min.js" type="text/javascript"></script>
<script>
$(function(){
$("#mydiv").click(function(){
var save_status = $(this).siblings(".save-status").next();
save_status.append('<img src="images/loading-small.gif" width=30 />');
alert(save_status);
});
});
</script>
<body>
<div id="mydiv">
<div></div>
<div></div>
<div class="save-status"></div>
</div>
</body>
The differences are the quotes and use ".next()"
区别在于引号和使用“.next()”