如何将jQuery元素选择应用于字符串变量
我有一些html被提取到一个字符串var,并希望然后在该字符串上使用jQuery元素选择。 这可能吗?
例如:
HTML:
jQuery的:
$('div.message').each(function(i, item) { myHtml = $(this).html(); //select tag attributes here )};
所以在这个例子中,我想从myHtml
的标签中提取
id
和href
。
谢谢
如果我理解正确,你在字符串变量中有HTML代码,并想在其中查询?
// Suppose you have your HTML in a variable str var str = ') - 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();
'; // You query the DOM fragment created by passing the string to jQuery function. // $(
你可以这样做:
var aID = $('div.message a.link').attr('id'); var aHREF = $('div.message a.link').attr('href');
有一个jQuery插件( 这里 ),你可以用它来解析一个字符串作为XML DOM,然后使用jQuery来查询它。 它需要是XML,而不是您有时在HTML中看到的“轻松”类型的XML(即您需要围绕属性值引用)。
如果您需要在结构中处理多个项目,则可以执行此操作
$('div.message').each(function(i, item) { // find desendant of the item using "find" var alink = $(this).find('a.link'); // Process the item var id = alink.attr('id'); var href = alink.attr('href'); )};