我有以下字符串
str ='<div id="example">Text</div><div id="test">Test</div>';
如何使用 jQuery 获取示例和测试内容。
最佳答案
需要将文本转为jQuery对象,然后使用标准的遍历方法
str ='<div id="example">Text</div><div id="test">Test</div>';
var live_str = $('<div>',{html:str});
var example = live_str.find('#example').text();
// example variable now holds 'Text'
var test = live_str.find('#test').text();
// example variable now holds 'Test'
演示在 http://jsfiddle.net/gaby/FJSm6/
如您所见,我将字符串设置为另一个元素的 html,否则 div 将位于顶层,您将无法使用 .find()
遍历它们。
关于jquery - 从字符串中获取 div 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6609655/