我将一些 html 提取到字符串 var,然后想在该字符串上使用 jQuery 元素选择。这可能吗?
例如:
HTML:
<div class=message>
This is a message. Click <a class=link id=link1 href=example.com>here</a>
</div>
jQuery:
$('div.message').each(function(i, item) {
myHtml = $(this).html();
//select <a> tag attributes here
)};
所以在这个例子中,我想提取 id
和href
来自<a>
标签 myHtml
。
谢谢
最佳答案
如果我理解正确的话,您的字符串变量中有 HTML 代码,并且想要在其中进行查询?
// Suppose you have your HTML in a variable str
var str = '<div class="message">This is a message. Click '
+ '<a class="link" id="link1" href="example.com">here</a></div>';
// You query the DOM fragment created by passing the string to jQuery function.
// $(<string>) - creates a DOM fragment (string must contain HTML)
var anchor = $('a', $(str));
// Then you can retrieve individual properties and/or contents:
var id = anchor.attr('id');
var href = anchor.attr('href');
var text = anchor.text();
关于jquery - 如何将 jQuery 元素选择应用于字符串变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2421719/