39

使用 jQuery。我有以下html:

<input type="checkbox" name='something' value='v1' /> All the world <br />

我怎么会只得到文字。我应该使用什么选择器?(我需要“全世界”)

我也无法触摸HTML...

4

4 回答 4

69

尝试使用 DOM 函数 .nextSibling选择下一个节点(包括文本节点)并用于nodeValue获取文本All the world

$(':checkbox')[0].nextSibling.nodeValue
于 2012-10-22T19:00:06.257 回答
7

只需使用plain-JavaScript nextSibling,尽管您必须“退出” jQuery 才能使用该方法(因此使用[0]):

var text = $('input:checkbox[name="something"]')[0].nextSibling.nodeValue;

JS 小提琴演示

我终于意识到我的另一个建议出了什么问题,该建议已得到修复:

var text = $('input:checkbox[name="something"]').parent().contents().filter(
    function(){
        return this.nodeType === 3 && this.nodeValue.trim() !== '';
    }).first().text();

JS 小提琴演示

并确保您只textNodes之前获得br(尽管坦率地说,这变得过于复杂,第一个建议更容易工作,而且我怀疑可靠):

var text = $('input:checkbox[name="something"]').parent().contents().filter(
    function(){
        return this.nodeType === 3 && this.nodeValue.trim() !== '' && $(this).prevAll('br').length === 0;
    }).text();

JS 小提琴演示

于 2012-10-22T18:59:02.273 回答
3

如果您label在标记中添加了 a(推荐),您可以这样做:

HTML

<input type="checkbox" id="something" name="something" value="v1" /><label for="something">All the world</label> <br />

JS

var text = $( '#something ~ label:first' ).text();
于 2012-10-22T19:01:44.853 回答
0

只是在一个老问题的例子中折腾,将文本包装在标签中

$('input[type="checkbox"]')
  .each(function(index, el) {
    var textNode = $(el.nextSibling);
    if (textNode[0].nodeType == Node.TEXT_NODE) {
      let checkwrap = $(el).wrap('<label class="found"></label>').closest('.found');
      textNode.appendTo(checkwrap);
    }
  });
.found {
  border: solid cyan 1px;
  color: blue;
  padding: 0.5em;
  display: inline-block;
  margin: 0.3em;
}

label.found {
  color: lime;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<span>in a span</span>
<input type="checkbox" name='something' value='v1' /> All the world <br />
<input type="checkbox" name='something2' value='v2' /> All the world 2 <span>in a span</span><br />
<input type="checkbox" name='something3' value='v3' /> All the world 3 <span>in a span</span>
<input type="checkbox" name='something4' value='v4' /> All the world 4<span>in a span also</span>

在那里,包裹在标签中,哦等等,这是一个答案,只需nextSibling要按类型隔离

于 2019-02-25T17:50:32.560 回答