-1

我正在尝试学习一些 jQuery/JS,但遇到了一个我无法解决的问题。我有一个这样的文字:

blablablabla <b data-start="" data-end="">#foo</b> blablabla" 

请注意,我在此文本中可以有多个标签。


我需要将属性编辑为正确的值,所以我正在构建一个方法来做到这一点:

// "str" isn't static, but for pratical purposes, I'm using this as static. 
str = 'blablablabla <b data-start="" data-end="">#foo</b> blablabla'

str.children('b').each(function(i){
      $(this).attr('data-start', '');
      $(this).attr('data-end', '');
})

如您所见,我不知道如何执行上面的代码。我虽然使用:

str.children('b').each(function(i){
          var start = $(this).indexOf('#');
          $(this).attr('data-start', '');
          $(this).attr('data-end', '');
    })

但这将返回 index 1,因为我在b标签内获取文本索引,而不是在所有文本本身内。那么,我该如何解决这个问题并获得“b”的初始位置和“b”的最终位置(不包括标签本身)?

4

1 回答 1

2

嗯..可能是这样的.. jsfiddle链接

<span id="test" >
blablablabla <b data-start="" data-end="">#foo</b> blablabla" 
</span>

和jQuery ..

var str = $("#test").text();
var strB = $("#test b").text();
$("#test b").attr("data-start", str.indexOf(strB) );
$("#test b").attr("data-end", (str.indexOf(strB) + strB.length-1));
alert($("#test").html())
于 2013-10-20T14:09:58.260 回答