I have the following string
我有下面的字符串
str ='<div id="example">Text</div><div id="test">Test</div>';
how can I get the example and test content with jQuery.
如何获得示例并使用jQuery测试内容。
3 个解决方案
#1
7
You need to convert the text to a jQuery object and then use standard traversing methods
您需要将文本转换为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'
demo at http://jsfiddle.net/gaby/FJSm6/
演示http://jsfiddle.net/gaby/FJSm6/
As you see i set the string as the html of another element, because otherwise the divs would be at the top level and you would not be able to traverse them with .find()
..
如您所见,我将字符串设置为另一个元素的html,因为否则div将位于顶层,您将无法使用.find()遍历它们。
#2
3
You can always create min-DOMs (if you wish) by passing a valid HTML to jQuery:
您可以通过将有效的HTML传递给jQuery来创建mindom(如果您愿意):
$(str).wrap('<p>').parent().find('div').text();
so:
所以:
var textContent = $(str).wrap('<p>').parent().find('#example').text();
var testContent = $(str).wrap('<p>').parent().find('#test').text();
#3
0
The easiest would be to store the content in a var and work with that:
最简单的方法是将内容存储在var中,并使用它:
var example = $('#example').text(), test = $('#test').val();
You can also get the contents using .html() if you would like to also grab the html tags if necessary.
您还可以使用.html()来获取内容,如果需要的话,还可以获取html标记。
#1
7
You need to convert the text to a jQuery object and then use standard traversing methods
您需要将文本转换为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'
demo at http://jsfiddle.net/gaby/FJSm6/
演示http://jsfiddle.net/gaby/FJSm6/
As you see i set the string as the html of another element, because otherwise the divs would be at the top level and you would not be able to traverse them with .find()
..
如您所见,我将字符串设置为另一个元素的html,因为否则div将位于顶层,您将无法使用.find()遍历它们。
#2
3
You can always create min-DOMs (if you wish) by passing a valid HTML to jQuery:
您可以通过将有效的HTML传递给jQuery来创建mindom(如果您愿意):
$(str).wrap('<p>').parent().find('div').text();
so:
所以:
var textContent = $(str).wrap('<p>').parent().find('#example').text();
var testContent = $(str).wrap('<p>').parent().find('#test').text();
#3
0
The easiest would be to store the content in a var and work with that:
最简单的方法是将内容存储在var中,并使用它:
var example = $('#example').text(), test = $('#test').val();
You can also get the contents using .html() if you would like to also grab the html tags if necessary.
您还可以使用.html()来获取内容,如果需要的话,还可以获取html标记。