Why does this jQuery click event not work?
I have this 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>
and I have this 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
});
});
With this function I am attempting to show the <ul>
when the input is clicked. Nothing happens when I click it. Any ideas why?
Edit: I just figured out what the problem was, I am inserting the html after the page loads so I need to do:
$('.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
});
});
Make sure you wait until the document is ready with
$(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
});
});
});
Since you are inserting the HTML into the document after the initial, you will need to use jQuery live() to bind the event to the new element.
$(this).next(":hidden").show();
Try:
$(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
});
});
});
精彩评论