简体   繁体   English

jquery 附加 div onclick 第一次不工作

[英]jquery appended div onclick not work first time

this is my code这是我的代码

html: html:

<input type="text" class="js-input">  
<div class="js-autofill"></div>

jquery: jquery:

var myarray = ['apple' , 'orange'];
myarray.forEach(element => {
$('.js-autofill').append(
`<div class="js-item" data-value="`+element+`">` +element+ `</div>`
)
})

$(document).on('click','.js-item',function(){
$('.js-input').val($(this).attr('data-value'))
})

problem is .js-item onclick not working at firsttime - it's work when i doubleclick i can't find why问题是.js-item onclick 第一次不工作 - 当我双击时它工作我找不到原因

You need to change .val() to .text() for the div click.您需要将.val()更改为.text()以进行 div 单击。

From Docs来自文档

The .val() method is primarily used to get the values of form elements such as input, select and textarea. .val()方法主要用于获取表单元素的值,例如 input、select 和 textarea。 When called on an empty collection, it returns undefined.当在空集合上调用时,它返回未定义。

$('.js-input').val($(this).text())

2 - Your div string in append has mismatch quotes, the correct order should be as below. 2 - 您在 append 中的 div 字符串有不匹配的引号,正确的顺序应该如下所示。

`<div class='js-item' data-value='` + element + `'>` + element + `</div>`

Also its helpful for you to read: When should I use double or single quotes in JavaScript?阅读它也很有帮助: 我什么时候应该在 JavaScript 中使用双引号或单引号?


Working code below下面的工作代码

 var myarray = ['apple', 'orange']; myarray.forEach(element => { $('.js-autofill').append( `<div class='js-item' data-value='` + element + `'>` + element + `</div>` ) }) $(document).on('click', '.js-item', function() { $('.js-input').val($(this).text()) })
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type="text" class="js-input"> <div class="js-autofill"></div>

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

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