我得到的变量值始终遵循以下格式:
"<div>
</div>
<div>
<span style="font-family:tahoma,geneva,sans-serif;"><span>VALUE 1</span></span></div>
<div>
<strong><span style="font-family:tahoma,geneva,sans-serif;">VALUE 2</span></strong></div>
<div>
<span style="font-family:tahoma,geneva,sans-serif;"> </span>VALUE 3</div>
"
如何使用JavaScript(不是jQuery或其他库)获得 VALUE 1 , VALUE 2 和 VALUE 3 ?
NB:
在控制台中,我得到了这些值(我称之为 b )
typeof(b)
返回string
答案 0 :(得分:3)
使用jQuery
的最简单方法。
var a = '<div>\
</div>\
<div>\
<span style="font-family:tahoma,geneva,sans-serif;"><span>VALUE 1</span></span></div>\
<div>\
<strong><span style="font-family:tahoma,geneva,sans-serif;">VALUE 2</span></strong></div>\
<div>\
<span style="font-family:tahoma,geneva,sans-serif;">au </span>VALUE 3</div>'
var HTML = $.parseHTML(a)
var val1 = $(HTML[1]).find('span span').text()
var val2 = $(HTML[2]).find('span').text()
$(HTML[3]).find('span').remove()
var val3 = $(HTML[3]).text()
console.log(val1, val2, val3)
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
答案 1 :(得分:2)
innerHTML
将字符串添加到temp
元素并使用DOM-api
来操作数据。
使用 'span[style]'
选择器仅获取具有style
属性的span元素。
var str = '<div>\
</div>\
<div>\
<span style="font-family:tahoma,geneva,sans-serif;"><span>VALUE 1</span></span>\
</div>\
<div>\
<strong><span style="font-family:tahoma,geneva,sans-serif;">VALUE 2</span></strong></div>\
<div>\
<span style="font-family:tahoma,geneva,sans-serif;">VALUE 3</span></div>';
var div = document.createElement('div');
div.innerHTML = str;
var spanElems = div.querySelectorAll('span[style]');
var spans = [].map.call(spanElems, function(el) {
return el.textContent.trim();
}).filter(Boolean);
console.log(spans);
&#13;
答案 2 :(得分:1)
您可以将字符串另存为变量,然后使用htmlString.match(/VALUE \d+/gmi)
答案 3 :(得分:1)
<强>更新强>:
如果输入是有效的HTML字符串,您可以使用此技巧解析(不是jQuery或其他库):
var your_string = `<div> </div><div><span style="font family:tahoma,geneva,sans-serif;"><span>VALUE 1</span>fgfgfg</span></div><div><strong><span style="font-family:tahoma,geneva,sans-serif;">VALUE 2</span></strong></div><div><span style="font-family:tahoma,geneva,sans-serif;"> </span>VALUE 3</div>`
var obj_evaluator = document.createElement("div");
obj_evaluator.innerHTML = your_string;
// get the list of div
var list_div = obj_evaluator.getElementsByTagName('div');
var value1 = (list_div[1].firstChild.firstChild.textContent); //value 1
var value2 = (list_div[2].firstChild.firstChild.textContent); //value 2
var value3 = (list_div[3].lastChild.textContent); //value 3
// create an array
var result = [value1,value2,value3]
// print result
console.log(result);
&#13;
旧回答(由于VALUE 3错误,但如果所有VALUE都在&#39; span&#39; 之内,那么这是正确答案! ):
var obj_evaluator = document.createElement("div");
obj_evaluator.innerHTML = your_string;
// debug row
console.log(obj_evaluator);
var list_span = obj_evaluator.getElementsByTagName('span');
for (var i = 0; i < list_span.length; i++) {
console.log(list_span[i].innerHTML);
// here you can print other info of the node
}