JavaScript HTML值转换为数组

3

$("#keyword-content").html()

Produces

  <p>
    javascript
  </p>
  <p>
    ruby
  </p>
  <p>
    python
  </p>

我该如何将它转换为["javascript", "ruby", python"]
2个回答

6
您可以使用map方法:
var arr = $('#keyword-content p').map(function(){
      return $(this).text()
}).get()

1
谢谢@undefined,这是一个非常简洁的模式。等待接受。 - Dru

0

类似这样:

var myArray = [];

$("#keyword-content p").each(function(index,item) {
    myArray.push($(item).text());
});

谢谢 @Matt,但是这会抛出一个错误 #<HTMLParagraphElement>没有'text'方法。在来到SO寻求帮助之前,我尝试过类似的underscore.js的东西。 - Dru

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接