javascript - 为什么这个 jQuery 点击事件不起作用?

标签 javascript jquery html debugging

我有这个 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
    });
});

通过这个函数,我试图显示 <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
        });
    });
});

关于javascript - 为什么这个 jQuery 点击事件不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6348195/

相关文章:

javascript - 匹配 JavaScript 数组中的值

javascript - JQuery 中未检测到单选按钮更改

javascript - Jquery Ajax 改变 html 表的内容

html - 在 R 中抓取 html 表及其 href 链接

javascript - jQuery 求和单选按钮值和文本输入值?

javascript - 等待循环结束然后在 Javascript 中执行操作的最优雅的方法是什么?

javascript - jQuery 中的 div 标签

javascript - 我有一个固定的 div,我正在使用 jquery 在滚动时淡出。它工作正常,但如果我半途而废并引用 div 显示的页面

asp.net - asp.net Web 应用程序中的 HTML 内容授权

javascript - 在 Swift 中使用 UIWebView.stringByEvaluatingJavaScriptFromString 删除 html 中带有 <noscript> 标签的所有元素