JQuery: select <p> inside an input checkbox type

JQuery: select <p> inside an input checkbox type

我想更改我的 <p> 标签样式。

我的html代码:

<input type="checkbox"><p> paragraph</p>

jQuery:

$('ul.list').on("click", "input", function() {
    if ( $(this).is(':checked') ) {
        $(this).find('p').css("text-decoration", "line-through");
    } else {
        $(this).find('p').css("text-decoration", "none");
    }
});

使用next()函数。

 $('ul.list').on("click", "input:checkbox", function () {
    $(this)
        .next('p')
        .css("text-decoration", this.checked ? "line-through" : "none");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<ul class="list">
  <li>
    <input type="checkbox">
    <p>paragraph</p>
  </li>
</ul>

或者你可以使用siblings()函数

$('ul.list').on("click", "input", function() {
    $(this).siblings('p')
        .css("text-decoration", this.checked ? "line-through" : "none")
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<ul class="list">
  <li>
    <input type="checkbox">
    <p>paragraph</p>
  </li>
</ul>

您的段落不在您的 input 标签内。尝试使用 next 而不是 find

$('ul.list').on("click", "input", function(){

    if( $(this).is(':checked') ) {
        $(this).next('p').css("text-decoration" ,  "line-through");
    } else {
        $(this).next('p').css("text-decoration", "none");
    }
});

https://api.jquery.com/next/

<input> 元素是空元素 (see this answer),因此不应包含任何元素。您可以使用 .next().siblings() 来获得您想要的效果。

$('ul.list').on("click", "input", function(){
  if( $(this).is(':checked') ) {
    $(this).next('p').css("text-decoration" ,  "line-through");
  } else {
    $(this).siblings('p').css("text-decoration", "none");
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="list">
  <li>
    <input type="checkbox"><p> paragraph</p>
  </li>
</ul>

您可以针对该行为使用 CSS 唯一解决方案:

input[type=checkbox]:checked + p {
  text-decoration: line-through;
}
<ul class="list">
  <li>
    <input type="checkbox">
    <p>paragraph</p>
  </li>
</ul>