1

我一直在使用 JQuery,我在 JFiddle 上尝试了我的代码,它运行良好,但是当我在我的网站上这样做时,它根本不起作用,基本上我需要在我的用户列表中的列表项被点击时发送一个事件.

HTML

<!DOCTYPE html>
<html>
    <head>
        <link rel="stylesheet" href="https://dl.dropbox.com/s/r5pzakk4ikvck3t/style.css?dl=1">
        <script src="https://www.dropbox.com/s/2hdvqa4ma51m0pw/jquery-1.9.0.min.js?dl=1"></script>
        <title>Chat</title>
    </head>
    <body>
        <div id="userlist-container">
            <div id="userlist-title">User List</div><br />
        </div>

        <div id="main-container">
            <div id="messages">
            </div>
        </div>

        <div id="control-container">
            <input type="text" id="TxtMessage" placeholder="Message" onKeyPress="SendMsg(event)" style="text-align:center;" >
        </div>

        <div id="alert-container" hidden="hidden">
            <div id="alert-main">
                <span id="alert-content"></span>
            </div>
        </div>
     </body>
</html>

Javascript

$("#userlist-container > li").click(function(e) {
    alert("TEST");
    var username = "@" + this.html + " ";
    $("TxtMessage").value(username);
    $("TxtMessage").focus();
});

编辑:

页面加载后,它会连接到服务器并添加<li>lalala</li>userlist-container.

4

2 回答 2

6

您在绑定中的选择器是错误的:

$("#userlist-container > li")

没有li你的 HTML 是:

<div id="userlist-container">
    <div id="userlist-title">User List</div><br />
</div>

此外,您似乎缺少#事件中的 id 选择器。

所以你的事件可能应该类似于:

$("#userlist-container > div").click(function(e) {
    alert("TEST");
    var username = "@" + this.html + " ";
    $("#TxtMessage").value(username);
    $("#TxtMessage").focus();
});

编辑

should have probably told you guys that once it does some wizzard stuff, li's get added so there are actually li tags in there.

I added your code to a fiddle and no li tags seem to be added when inspecting the DOM.

The fiddle

That could be just the fiddle though, not sure. I'm assuming if the li tags are injected that you need to use delegate binding using on if you are using jquery 1.7 or later or delegate if you are using 1.6 or earlier.

Similar to this:

// jQuery 1.7 or later
$("#userlist-container").on("click", ">li", function(){
    alert("TEST");
    var username = "@" + this.html + " ";
    $("#TxtMessage").value(username);
    $("#TxtMessage").focus();
});

// jQuery 1.4.3 to 1.6.x
$("#userlist-container").delegate(">li", "click", function(){
    alert("TEST");
    var username = "@" + this.html + " ";
    $("#TxtMessage").value(username);
    $("#TxtMessage").focus();
});
于 2013-02-02T00:00:52.233 回答
1

您的选择器错误,添加 # 前缀表示 id

$("#TxtMessage").value(username);
$("#TxtMessage").focus();

如果您的点击事件甚至没有触发,请确保在加载文档后附加事件

$(document).ready(function(){  
    //code here  
}); 
于 2013-02-01T23:58:54.173 回答