[英]jQuery Inconsistent text() val() selection and populating input
$name
and $id
are only copied properly a small portion of the time. $name
和$id
仅在一小部分时间内正确复制。 Selection is expected to populate the input #user_search
but selections come up undefined. 预期选择将填充输入#user_search
但选择未定义。 The text is copied properly at what seems like random... 文本以随机的方式正确复制。
HTML 的HTML
<input type="text" name="user" id="user_search" autocomplete="off"
class="user_live form-control" data-parsley-required="true" value="" />
<div id="user_result"></div>
HTML Added to DOM HTML已添加到DOM
<div id="user_result" style="display: block;">
<div class="showResult row">
<div class="box-body">
<a class="user_id" id="353">
<div class="col-lg-3 col-md-3 col-xs-3">
<img height="50px" src="/assets/user_1.jpg">
</div>
<div class="col-lg-9 col-md-9 col-xs-9">
<span class="name">First Last</span>
</div>
</a>
</div>
</div>
<div class="showResult row">
<div class="box-body">
<a class="user_id" id="200">
<div class="col-lg-3 col-md-3 col-xs-3">
<img height="50px" src="/assets/user_2.jpg">
</div>
<div class="col-lg-9 col-md-9 col-xs-9">
<span class="name">First Last</span>
</div>
</a>
</div>
</div>
</div>
JS JS
$('#user_result').on('click',function(e){
var $clicked = $(e.target);
var $name = $clicked.find('.name').text(); //removed .html($name)
alert($name);
$('#user_search').val($name);
});
The issue lies with e.target
and .find()
not working quite right with that layout. 问题在于e.target
和.find()
在该布局下无法正常工作。 Try this: 尝试这个:
$('#user_result').on('click',function(e){
var $name = $(e.target).closest('.showResult').find('.name').text();
alert($name);
$('#user_search').val($name);
});
https://jsfiddle.net/feab9ms0/ https://jsfiddle.net/feab9ms0/
When the click event is triggered, the actual target is the img
tag and not the div
itself. 触发click事件时,实际目标是img
标签,而不是div
本身。 Since the element with class .name
is not contained in the img
, you do not get any matching results back. 由于img
不包含具有.name
类的元素,因此不会返回任何匹配结果。 Therefore you need to use the .closest
to navigate to the least parent tag which contains the img
tag. 因此,您需要使用.closest
导航到包含img
标签的最小父标签。
$("#user_result").on("click",function(e){
var $clicked = $(e.target);
var $name = $clicked.closest(".box-body").find('.name').text();
alert($name);
$('#user_search').val($name);
});
在分配给此处html($name).text()
之前,您尚未初始化$name
,这导致t将该决策呈现为未定义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.