解析 HTML 字符串以使用 Javascript 获取元素的内容

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4354589/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 11:09:19  来源:igfitidea点击:

Parse an HTML string to get contents of elements with Javascript

javascriptjquerystringparsingjeditable

提问by Chris Armstrong

I have the following string that contains several elements:

我有以下包含几个元素的字符串:

'<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>'

What would be the best way to parse this out to 5 variables?

将其解析为 5 个变量的最佳方法是什么?

EDIT

编辑

For clarity, here's the full code, I'm creating a custom input type for jEditable that allows me to inline edit a vcard.

为清楚起见,这里是完整代码,我正在为 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);
  }

});

回答by Jakub Hampl

Create an element, put it into that element with innerHTMLand select them out with querySelector.

创建一个元素,用 将其放入该元素中,innerHTML然后用 选择它们querySelector

So assuming you wanted to use just plain old js:

因此,假设您只想使用普通的旧 js:

el = document.createElement('p');
el.innerHTML = '<span class="fn" id="fn1">Matthew</span> ... <span class="dday" id="dday1">2000</span>'
el.querySelector('.fn').innerText // = 'Matthew'
el.querySelector('#fn1').outerHTML // = "<span class="fn" id="fn1">Matthew</span>"

Which translates almost directly into jQuery:

这几乎可以直接转换为 jQuery:

el = $('<p />').html('<span class="fn" id="fn1">Matthew</span> ... <span class="dday" id="dday1">2000</span>');
el.find('.fn').text() // = 'Mathew'

回答by istruble

First find the elements then grab data from each element using a combination of attr()and text()or html().

首先找到元素,然后使用attr()text()html()的组合从每个元素中获取数据。

You can find the elements by using the usual selectorstring or the raw string you mentioned in the question.

您可以使用通常的选择器字符串或您在问题中提到的原始字符串来查找元素。

var target_string = # ... raw string or selector for '#interesting span'

var $data = $(target_string);

# adjust this to produce the format you want
var data = {};
$data.each(function () {
    var $t = $(this);
    data[$t.attr('id')] = {id: $t.attr('id'),
                           class: $t.attr('class'),
                           value: $t.text()};  # or .html()
});

# you can access this example data via the id values in the html
data['spouse'] # or
data.spouse

回答by Jason McCreary

Using jQuery, check out text()

使用 jQuery,查看text()

// get text from all spans
var all_text = $('span').text();
// break out into an array of values
var values = all_text.split(' ');

NOTEthis will get the textfor all spantags on the page. So you will want to make a better selector and probably assign this to variables in a better way than split().

注意这将获得页面上所有标签的文本span。因此,您将想要制作一个更好的选择器,并且可能以比split().

回答by kobe

Use jQuery's .html.           

使用 jQuery 的.html.