对不同的html li对象使用相同的jquery函数

我正在尝试创建一个将文本从特定列表元素复制到输入表单的函数。我正在苦苦挣扎的是,我的函数只是复制所有文本而不是特定元素。是否有人建议如何正确(动态)指示列表对象?谢谢!

<!--Copy into Form Field-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

  <!--Input field and list items-->
<input type="text" class="form-control" id="input2" placeholder="Input" size="200">

<li class="test" id="li1">test</li>
<li class="test" id="li2">brumbo</li>

  <!--Function to Copy list items into input field-->
<script type="text/javascript">
$(function () {
    $('.test').on('click', function () {
        var text = $('#input2');

        text.val(text.val() +','+ $('.test').text());    
    });
});
</script>

点击后的输出测试应该是:测试(而不是testbrumbo)

评论
  • 盛水冬
    盛水冬 回复

    .text() returns the combined text content of all elements in your collection, and $('.test') has selected all elements with that class in your document.

    You want $(this).text(), to only get the text of the current element that you are currently handling the click event for.

  • 巢香莲
    巢香莲 回复

    You need change $('.test').text() to $(this).text() for get current li as

    $(function () {
        $('.test').on('click', function () {
            var text = $('#input2');
    
            text.val(text.val() +','+ $(this).text());    
        });
    });
    <!--Copy into Form Field-->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
      <!--Input field and list items-->
    <input type="text" class="form-control" id="input2" placeholder="Input" size="200">
    
    <li class="test" id="li1">test</li>
    <li class="test" id="li2">brumbo</li>
    
      <!--Function to Copy list items into input field-->
    <script type="text/javascript">
    
    </script>