JQuery:在输入复选框类型中选择<p>

时间:2015-08-11 17:54:19

标签: jquery checkbox input selector

我想更改<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");
    }
});

4 个答案:

答案 0 :(得分:2)

<input>元素是一个void元素(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>

答案 1 :(得分:2)

您可以对该行为使用仅CSS解决方案:

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

答案 2 :(得分:1)

您的段落不在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/

答案 3 :(得分:0)

使用 next() 功能。

&#13;
&#13;
 $('ul.list').on("click", "input:checkbox", function () {
    $(this)
        .next('p')
        .css("text-decoration", this.checked ? "line-through" : "none");
});
&#13;
<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>
&#13;
&#13;
&#13;

或者您可以使用 siblings() 功能

&#13;
&#13;
$('ul.list').on("click", "input", function() {
    $(this).siblings('p')
        .css("text-decoration", this.checked ? "line-through" : "none")
});
&#13;
<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>
&#13;
&#13;
&#13;

相关问题