簡體   English   中英

jQuery的點擊功能不觸發

[英]jquery click function in not fire

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <script src="jq/jquery-1.10.2.js" type="text/javascript"></script>
    <title></title>
    <script type="text/javascript" language="javascript">
        $(document).ready(function () {

            $("table tr td").click(function () {

                var div_top = $(this).position().top;
                var div_left = $(this).position().left;

                var new_div = "<div style='position:absolute;z-index:2;top:" + div_top + "px;left:" + div_left + "px;width:30px;height:23px;background:red;margin:0px auto;'></div>";
                $(".main").html(new_div + $(".main").html());
            });
        });
</script>
</head>
<body>
    <form id="form1" runat="server">
    <div class="main">
        <table class="tbl-bottom">
            <tr><td>temp</td><td></td><td></td></tr>
            <tr><td></td><td>temp</td><td></td></tr>
        </table>
    </div>
    </form>
</body>
</html>

第一次單擊表的“ td”時,然后在該“ td”中顯示div,但是單擊另一個“ td”后,單擊功能不會觸發。

您完全可以點擊以下內容重寫表格:

 $(".main").html(new_div + $(".main").html()); //.html() rewrite table

因此,包含單擊事件的表不再存在。

嘗試改用.prepend

 $(".main").prepend(new_div);

小提琴: http://jsfiddle.net/ezyLV/2/


重新讀取當前代碼后,可能不需要進行此編輯

仍然保留以防萬一,可能很有用。

現在,該表不會在每次單擊時都被重寫,因此您需要防止div在每次單擊前都被添加。

為此,只需將div轉換為jQuery對象並將其移到click事件之外:

$(document).ready(function () {
    var new_div = $("<div style='position:absolute;z-index:2;width:30px;height:23px;background:red;margin:0px auto;'></div>");
    $("table tr td").click(function () {
         var div_top = $(this).position().top;
         var div_left = $(this).position().left;

         new_div.css({top : div_top, left : div_left});

         $(".main").prepend(new_div);
     });
});

這樣,您就不必在每次單擊時都添加一個新的div,而只需移動它並更改其CSS。

小提琴: http://jsfiddle.net/ezyLV/1/

您需要使用事件委托,因為您要反復添加表。

更改:

$("table tr td").click(function () {

至:

$('div.main').on('click', "table tr td", function () {

jsFiddle示例

您正在用此行替換所有html ...

$(".main").html(new_div + $(".main").html());

這會導致您失去點擊處理程序。

您應該追加新的div,而不替換所有的html。 就像是...

$('.main').append(new_div);

我認為這會起作用:

$(document).ready(function () {

            $("table tr td").click(function () {

                var div_top = $(this).position().top;
                var div_left = $(this).position().left;

                var new_div = "<div style='position:absolute;top:" + div_top + "px;left:" + div_left + "px;width:30px;height:23px;background:red;margin:0px auto;'></div>";
                $(this).html(new_div);
            });
        });

我認為您想在<td>添加new_div 這就是為什么您使用.html()的原因。 在其他情況下,您想使用附加

帶有html()的OP

帶附加示例

嘗試這個:

$('td').each(function(){
     $(this).click(function(){
        ......
     });
});

您的代碼位於每個函數中。

這應該遍歷頁面上的所有單元格。

嘗試用$(this).html(new_div);替換... $(“。main”)。html ....等。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM