use*_*688 6 jquery jquery-selectors
我有一些html被提取到一个字符串var,并希望然后在该字符串上使用jQuery元素选择.这可能吗?
例如:
HTML:
<div class=message>
This is a message. Click <a class=link id=link1 href=example.com>here</a>
</div>
Run Code Online (Sandbox Code Playgroud)
jQuery的:
$('div.message').each(function(i, item) {
myHtml = $(this).html();
//select <a> tag attributes here
)};
Run Code Online (Sandbox Code Playgroud)
因此,在这个例子中,我要提取id和href从<a>标签中myHtml.
谢谢
Mar*_*mic 10
如果我理解正确,你在字符串变量中有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();
Run Code Online (Sandbox Code Playgroud)