使用 Javascript 解析 HTML 字符串以获取元素内容
我有以下包含多个元素的字符串:
'<span class="fn" id="fn1">Matthew</span>
<span class="spouse" id="spouse1">Evelyn Ross</span>
<span class="bday" id="bday1">1456</span>
<span class="wday" id="wday1"></span>
<span class="dday" id="dday1">2000</span>'
将其解析为 5 个变量的最佳方法是什么?
编辑
为了清楚起见,这里是完整的代码,我正在为 jEditable 创建一个自定义输入类型,它允许我内联编辑 vcard。
$.editable.addInputType('person', {
element : function(settings, original) {
var fn = $('<input id="fn_"/>');
var bday = $('<input id="bday_" />');
var wday = $('<input id="wday_" />');
var dday = $('<input id="dday_" />');
var spouse = $('<input id="spouse_" />');
$(this).append(fn);
$(this).append(bday);
$(this).append(wday);
$(this).append(dday);
$(this).append(spouse);
/* Hidden input to store value which is submitted to server. */
var hidden = $('<input type="hidden">');
$(this).append(hidden);
return(hidden);
},
content : function(string, settings, original) {
var $data = $(string);
var data = {};
$data.each(function () {
var $t = $(this);
data[$t.attr('id')] = {
class: $t.attr('class'),
value: $t.text()};
});
alert(data.length());
$("#fn_", this).val('Name');
$("#bday_", this).val('Born');
$("#wday_", this).val('Married');
$("#dday_", this).val('Died');
$("#spouse_", this).val('Spouse');
},
submit: function (settings, original) {
var value = "<span class=fn>" + $("#fn_").val() + '</span>' + '<span class=spouse>' + $("#spouse_").val() + '</span>' + '<span class=bday>' + $("#bday_").val() + '</span>' + '<span class=wday>' + $("#wday_").val() + '</span>' +'<span class=dday>' + $("#dday_").val() + '</span>';
$("input", this).val(value);
}
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
创建一个元素,使用
innerHTML
将其放入该元素,并使用querySelector
选择它们。因此,假设您只想使用普通的旧 js:
这几乎直接转换为 jQuery:
Create an element, put it into that element with
innerHTML
and select them out withquerySelector
.So assuming you wanted to use just plain old js:
Which translates almost directly into jQuery:
首先找到元素,然后使用 attr() 和 text() 或
您可以使用常用的 选择器 字符串或您在问题中提到的原始字符串来查找元素。
First find the elements then grab data from each element using a combination of attr() and text() or html().
You can find the elements by using the usual selector string or the raw string you mentioned in the question.
使用 jQuery,查看 text()
注意 这将得到 span 标记的 >text。因此,您将想要制作一个更好的选择器,并且可能以比
split()
更好的方式将其分配给变量。Using jQuery, check out text()
NOTE this will get the text for all
span
tags on the page. So you will want to make a better selector and probably assign this to variables in a better way thansplit()
.使用 jQuery 的
.html
。Use jQuery's
.html
.