【问题标题】:Pass chosen (clicked) option to input box将选择(单击)选项传递给输入框
【发布时间】:2016-08-06 02:11:41
【问题描述】:

我有一堆输入建议,但我无法让它们成为可点击的。

<div class="search_native">
    <input type="text" name="native_input" id="native"/>
    <div id='output'></div>
</div>
$(document).ready(function() { 
    $("input").keyup(function(){
        $array = ['usa','france','germany','italy','poland'];
        $input_val = $("input[name='native_input']").val();
        $('#output').text('')
        r = new RegExp($input_val)
        for (i = 0; i < $array.length; i++) {
            if ($array[i].match(r)) {
                $('#output').append('<p class="match">' + $array[i] + '</p>')
            }
        }
    });

    $('.match').click(function(e) {
        alert('df');
    });
});

我尝试检查点击匹配是否有效,但没有。 alert() 不会弹出。为什么?还有一个问题;如果我需要将点击选项中的值放入输入框中,我可以为它做这样的事情吗(当已经点击时)?

$value = $(this).val();
$('#native').val() = $value;

【问题讨论】:

  • 第二个问题应该使用val()的setter:var value = $(this).val(); $('#native').val(value);
  • 可能将 keyup 更改为 on("keyup", function(){ 即可。

标签: javascript jquery select click


【解决方案1】:

在您的 $('.match') 选择器运行时,没有匹配的元素,因为这会在页面加载后立即发生。

您可以委托给父级或文档,因为这将在事件冒泡后捕获事件:

$(document).on('click', '.match', function(){
    alert('df');
    $value = $(this).text();
    $('#native').val($value);
});

.val() 语法需要新值作为参数。

【讨论】:

  • .click( function(){... 和 on('click' function(){..?..thought theu are same)
  • $value = $(this).val();如果我 alert($value) 它什么也不输出。为什么会这样?
  • 看起来你想要 $(this).text() 而不是 val – &lt;p&gt; 元素没有值。
猜你喜欢
  • 1970-01-01
  • 2020-07-05
  • 2018-10-01
  • 1970-01-01
  • 2018-01-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多