如何选择上一个类元素

时间:2021-01-14 20:21:04

html code

<tr>
 <td> 
   <input type='text' name='bbc[]'> <!-- array name input -->
   <ul class='popup'>
     <li> one </li>
     <li> two </li>
     <li> three</li> <!-- I want click copy value "three" and paste input -->
   </ul>
 </td>
</tr>
<tr>
 <td> 
   <input type='text' name='bbc[]'>
   <ul class='popup'>
     <li> one </li>
     <li> two </li>
     <li> three</li>
   </ul>
 </td>
</tr>

I want : click ul inside li copy text() or html() value and paste this outside input value.

我想:在li copy text()或html()值中单击ul并粘贴此外部输入值。

$('body .popup').hide();
    $('body').on('keyup','.name',function(){
        $(this).next().slideDown();
        $('body .popup li').click(function(){
            $(this).prev().css({background:'red'})
        });
    });
})

$(window).click(function(){
        $('.popup').slideUp(200);
});
$('body').on('click','.popup',function(e){
  e.stopPropagation();
});

I could get value but 'input' do not print

我可以获得价值,但“输入”不打印

jsfiddle

1 个解决方案

#1


2  

Input is the prev element of ul, not li. So you need to traverse to the current ul first.

输入是ul的主要元素,而不是li。所以你需要首先遍历当前的ul。

To get the current parent ul, you can use $(this).closest("ul")

要获取当前父级ul,可以使用$(this).closest(“ul”)

Then your final code will be,

然后你的最终代码将是,

$(function() {
  $('body .popup').hide();
  $('body').on('keyup', '.name', function() {
    $(this).next().slideDown();
    $('body .popup li').click(function() {
      $(this).closest("ul").prev().val($(this).text())
    });
  });
})

$(window).click(function() {
  $('.popup').slideUp(200);
});
$('body').on('click', '.popup', function(e) {
  e.stopPropagation();
})

Fiddle

#1


2  

Input is the prev element of ul, not li. So you need to traverse to the current ul first.

输入是ul的主要元素,而不是li。所以你需要首先遍历当前的ul。

To get the current parent ul, you can use $(this).closest("ul")

要获取当前父级ul,可以使用$(this).closest(“ul”)

Then your final code will be,

然后你的最终代码将是,

$(function() {
  $('body .popup').hide();
  $('body').on('keyup', '.name', function() {
    $(this).next().slideDown();
    $('body .popup li').click(function() {
      $(this).closest("ul").prev().val($(this).text())
    });
  });
})

$(window).click(function() {
  $('.popup').slideUp(200);
});
$('body').on('click', '.popup', function(e) {
  e.stopPropagation();
})

Fiddle

相关文章