我有一些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 )};
所以在这个例子中,我想从< a>中提取id和href. 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();