简体   繁体   English

将 JQuery DOM 元素保存为变量

[英]Saving a JQuery DOM element as a variable

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!谢谢!

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.问题在于你的报价。

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.要回答您的其他问题(根据标题和示例),您可以保存jQuery objectDOM element ,但它们不一样。 For example:例如:

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

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()”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM