简体   繁体   中英

How do I select the previous class element

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.

$('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

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

To get the current parent ul, you can use $(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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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