简体   繁体   English

如何在模板文字内获取JQuery对象?

[英]How do I get a JQuery object inside a template literal?

So often I have a JQuery object such as 所以通常我有一个JQuery对象,例如

var element = $('<h1>Title</h1>');

I will make some operations on it, and later, I want to embed it inside of a template literal, so it displays as if it were using the $().append from jquery. 我将对其进行一些操作,稍后,我想将其嵌入模板文字中,因此它显示为好像在使用jquery的$()。append。 Here is my attempt 这是我的尝试

var secondElement = $(`<div><div>${element}</div></div>`);
$('#someRandomDiv').append(secondElement);

This, as expected, outputs 预期结果

<div><div>[Object object]</div></div>

as it is referencing an object, not actually the HTML of the element. 因为它引用的是对象,而不是元素的HTML。 However I want it to be . 但是我希望如此。

<div><div><h1>Title</h1></div</div>

Is there a way of doing this? 有办法吗? Optimally it would still use the template literals, and of course, it is best if it uses native js/jquery functionality, rather than workarounds. 理想情况下,它仍将使用模板文字,当然,最好是使用本机js / jquery功能而不是变通办法。

You can access the underlying HTMLElement object by accessing element[0] , then what you want is the html string, which you can get with .outerHTML . 您可以通过访问element[0]来访问基础HTMLElement对象,然后所需的就是html字符串,可以通过.outerHTML获得。 So: 所以:

 var element = $('<h1>Title</h1>'); var secondElement = $(`<div><div>${element[0].outerHTML}</div></div>`); console.log(secondElement[0].outerHTML) // Logs: <div><div><h1>Title</h1></div></div> 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

Use jQuery methods instead 改用jQuery方法

 var element = $('<h1>Title</h1>'); var secondElement = $(`<div>`).append(element).wrap(`<div>`).parent(); console.log(secondElement[0].outerHTML) // Logs: <div><div><h1>Title</h1></div></div> 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

Try following code: 尝试以下代码:

var element = $('<h1>Title</h1>');
var secondElement = $(`<div><div>${element.prop('outerHTML')}</div></div>`);
$('#someRandomDiv').append(secondElement);

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

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