[英]Why does this jQuery click event not work?
我有这个 HTML:
<div id="studyTestContent" class="studyTestItem">
<input type="text" class="dropInput" size="15">
<ul class="inputDrop" style="display:none;">
<li class="dropDownItem">Si</li>
<li class="dropDownItem">y</li>
<li class="dropDownItem">con</li>
<li class="dropDownItem">el</li>
</ul>
</div>
我有这个 jQuery:
$('.dropInput').click(function() {
var offset = $(this).offset();
var height = $(this).height();
var width = $(this).width();
var top = offset.top + height + "px";
var right = offset.left + width + "px";
$(this).next().show();
$(this).next().css({
'position': 'absolute',
'right': right,
'top': top
});
});
有了这个 function 我试图在单击输入时显示<ul>
。 当我点击它时没有任何反应。 任何想法为什么?
编辑:我刚刚弄清楚问题出在哪里,我在页面加载后插入 html 所以我需要做:
$('.dropInput').live('click', function() {
var offset = $(this).offset();
var height = $(this).height();
var width = $(this).width();
var top = offset.top + height + "px";
var right = offset.left + width + "px";
$(this).next().show();
$(this).next().css({
'position': 'absolute',
'right': right,
'top': top
});
});
确保等到文件准备好
$(document).ready(function() {
// put all your jQuery goodness in here.
$('.dropInput').click(function() {
var offset = $(this).offset();
var height = $(this).height();
var width = $(this).width();
var top = offset.top + height + "px";
var right = offset.left + width + "px";
$(this).next().show();
$(this).next().css({
'position': 'absolute',
'right': right,
'top': top
});
});
});
由于您在初始之后将 HTML 插入到文档中,因此您需要使用 jQuery live() 将事件绑定到新元素。
$(this).next(":hidden").show();
尝试:
$(document).ready(function(){
$('.dropInput').click(function() {
var offset = $(this).offset(),
height = $(this).height(),
width = $(this).width(),
top = offset.top + height + "px",
right = offset.left + width + "px";
$(this)
.next('.inputDrop')
.show()
.css({
'position': 'absolute',
'right': right,
'top': top
});
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.