jQuery 基于深层子文本内容的选择器

jQuery selector based on deep children text content

这是我正在使用的 HTML 示例。

<html>
    <div class="parent-div">
        <ul>
            <li class="title">Color</li>
            <li>Red</li>
            <li class="title">Shape</li>
            <li>Squared</li>
        </ul>
    </div>
</html>

我想在以下列表项

中转换当前HTML

这是我目前尝试的方法:

$("html > div.parent-div > ul > li:contains('Color')")

但是它抛出异常:

Uncaught DOMException: Failed to execute 'querySelectorAll' on 'Document': html > div.parent-div > ul > li:contains('Color')' is not a valid selector.

不需要在jQuery选择器中写html

$("div.parent-div > ul > li:contains('Color')")

那是因为 htmldocument 相同。将 html 留在选择器之外。

$("div.parent-div > ul > li:contains('Color')")

jQuery 的内部工作是它使用 document.querySelectorAll。由于 document 是根,您不需要在选择器中再次指定它。如果这样做,它将失败,因为 HTML(文档)不包含名为 "HTML".

的元素

以下代码段将满足您的需求。

$("document").ready(function(){
  //select all the list elements with the class title
  $("div.parent-div > ul > li.title").each(function(){
    //concat the text of the title element and the next sibling into one string.
    var text = $(this).text() + ": " + $(this).next().text();
    $(this).html(text); //change the title element's html to set string
    $(this).next().detach(); //delete the value element from the DOM.
  })
 });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
    <div class="parent-div">
        <ul>
            <li class="title">Color</li>
            <li>Red</li>
            <li class="title">Shape</li>
            <li>Squared</li>
        </ul>
    </div>
</html>

我不知道这是怎么回事,但是你可以用这样的东西得到它:

var output = {};
var output_index = 0;
var last_title = "";

var allLi = $("#parent-div li");
var $this = null;

for(var i = 0; i < allLi.length; i++){
   $this = $(this);
   if($this).hasClass(title){
      last_title = $this.html();
   } else {
      output[last_title] = $this.html();
   }
})