.split()数据属性何时应该无效

时间:2016-04-27 11:11:59

标签: javascript jquery

我想.split(" ")数据属性值,但它返回空:

var bulletcontent = jQuery(this).closest("div").find("p").attr('data-bcontent');

// split content into words
var words = jQuery(bulletcontent).text().split(" ");

为什么这不起作用?

这是jsFiddle

6 个答案:

答案 0 :(得分:4)

请参阅小提琴:https://jsfiddle.net/43439o8o/2/

您不需要获取.text().attr()已经返回其内容:

var bulletcontent = jQuery(content).attr('data-bcontent');

// split content into words
var words = bulletcontent.split(" "); //Remove the .text() method

正如您在.attr() method docs所看到的,您可以使用它来返回或设置属性值:

  

获取匹配元素集中第一个元素的属性值,或为每个匹配元素设置一个或多个属性。

答案 1 :(得分:0)

更改此行:

var words = bulletcontent.split(" ");

答案 2 :(得分:0)

$(document).ready(function() {
  $(document).on("click", ".click", function() {
    // find the bullet content stored in p tag inside li
    var content = $(this).prev("p").attr('data-bcontent');//get the p attr
    alert(content)
    var words = content.split(' ')//split
    alert(words[0]);//alert first  value
    alert(words[1]);//alert second value
  });
});

DEMO

答案 3 :(得分:0)

您可以直接在字符串上使用split()函数:

var words = bulletcontent.split(" ");

例如,您可以看到此link

答案 4 :(得分:0)

.split()是Javascipt中的String方法,因此无需使用jQuery。只需在变量(String)旁边添加.split(' ')

.split()返回字符串数组取决于您希望如何删除原始字符串。

这应该适合你。

     var words = bulletcontent.split(" ");

答案 5 :(得分:0)

您可以使用:

var words = bulletcontent.split(" ");