如何将jQuery元素选择应用于字符串变量 [英] how to apply jQuery element selection to a string variable
本文介绍了如何将jQuery元素选择应用于字符串变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一些html提取到字符串var,然后想要仅在该字符串上使用jQuery元素选择.这可能吗?
I have some html extracted to a string var, and want to then use jQuery element selection just on that string. Is this possible?
例如:
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
)};
因此在此示例中,我想从myHtml
中的<a>
标记中提取id
和href
.
So in this example, I want to extract the id
and href
from the <a>
tag in myHtml
.
谢谢
推荐答案
如果我正确理解,您在字符串变量中包含HTML代码,并希望在其中进行查询?
If I understand correctly, you have HTML code in a string variable, and want to query within that?
// 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元素选择应用于字符串变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文