简体   繁体   English

为什么父母不在jQuery中工作?

[英]why parent is not working in jquery?

could you please tell me why parent function is not working properly ? 你能告诉我为什么parent函数不能正常工作吗?

here is my code 这是我的代码

https://jsbin.com/gefacenefi/edit?html,js,output https://jsbin.com/gefacenefi/edit?html,js,输出

 $(function () {

        $('.add').click(function () {
            $('.item').parent('li.nn').css('color', 'red');
        });

    });

Expected output this text to be red 预期输出此文本为红色

<li class="nn">bhiooo</li>

You are trying to call a parent of a different node. 您正在尝试调用其他节点的父节点。 Try this 尝试这个

$('.add').click(function () {
  $('.item').parent().siblings('li.nn').css('color', 'red');
});

Please do the following: 请执行以下操作:

$(function () {
    $('.add').click(function () {
      $('.item').parent().siblings('li.nn').css('color', 'red');
    });
});

Also you are not closing your li element properly. 另外,您没有正确关闭li元素。 The structure should be like following: 结构应如下所示:

<!DOCTYPE html>
<html>
<head>
   <meta charset="utf-8">
   <meta name="viewport" content="width=device-width">
   <title>JS Bin</title>
   <script src="https://code.jquery.com/jquery-2.1.4.js"></script>
</head>
<body>
   <button class="add">filler</button>
   <div>
      <ul>
         <li class="nn">bhiooo</li>
         <li class="m">hello22
            <ul class="item">
                <li class="abc">123</li>
                <li class="pp">12</li>
                <li class="abc">78</li>
                <li class="ac">13</li>
                </li>
            </ul>
         </li>
      </ul>
   </div>
</body>
</html>

Your ul .item is not under .nn . 你UL .item没有受到.nn

Change the HTML, or adapt you JS 更改HTML或改编JS

$('.item').parent().prev('li.nn').css('color', 'red');

Try the following code 试试下面的代码

$('.add').click(function () {
  $('.item').parents().find('.nn').css('color', 'red');
});

Here is the working jsfiddle: https://jsfiddle.net/nq9tzafz/ 这是工作中的jsfiddle: https ://jsfiddle.net/nq9tzafz/

I think it should helps you 我认为这应该对您有帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM