开发者

Why does this jQuery click event not work?

开发者 https://www.devze.com 2023-03-12 17:55 出处:网络
I have this HTML: <div id=\"studyTestContent\" class=\"studyTestItem\"> <input type=\"text\" class=\"dropInput\" size=\"15\">

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
            });
    });
});
0

精彩评论

暂无评论...
验证码 换一张
取 消