2013-10-22 18 views
1

當我單擊第一個td(即第1行,單元格1)它顯示警告框時,我在自己的自定義警報框中顯示數據,然後單擊時(行1,cell 2,row 2,cell 1,row 2,cell 2)它沒有顯示我的警報框,我認爲它把整個表格作爲一個div,但是我想在分別點擊每個td時顯示警報框,任何人都可以指導我如何做到這一點,請在這裏看到我的代碼http://jsfiddle.net/Ur5Xn/5/alertbox在點擊每個td時顯示數據

我的AJAX

$(document).ready(function(){ 
    function showAlertBox(){ 
    $("#alert").css("display","inherit"); 
    $("#content").addClass("back"); 
    } 
    function removeAlertBox(){ 
     $("#alert").css("display","none"); 
     $("#content").removeClass("back");   
    } 

    $("#alertClose").click(function(){ 
     removeAlertBox(); 
    }); 
    $("#alertShow").click(function(){ 
     showAlertBox(); 
    }); 
}); 

謝謝

+0

你可以指定文件只有一個ID一個元素。如果將其用作選擇器,則將相同的id分配給不同的元素將僅適用於一個元素 –

回答

1

將它作爲class,因爲id是唯一的。

<td class="alertShow">row 1, cell 1</td> 
<td class="alertShow">row 1, cell 2</td> 

這將工作,這裏是演示編輯。 http://jsfiddle.net/Ur5Xn/7/

$(".alertShow").click(function(){ 
    showAlertBox(); 
}); 
1

您應該爲每個td和相同的類分配不同的ID。然後使用該類作爲點擊選擇器。

$(".alertShowClass").click(function(){ 
     showAlertBox(); 
    }); 
1

標識應該是唯一的,只是第一個計數,所以$長度( 「#alertShow」)將永遠爲1

嘗試改變ID = 「alertShow」爲class =「alertShow」,並使用$(「。alertShow」)。click。

或者更好的一個,使用$('table')。on('click','td',function(){}),即delegated-events approach

1

Live Demo

使用Class,而不是在tabletdid

爲前:

<table border="1"> 
<tr> 
    <td class="alertShow">row 1, cell 1</td> 
    <td class="alertShow">row 1, cell 2</td> 
</tr> 
<tr> 
    <td class="alertShow">row 2, cell 1</td> 
    <td class="alertShow">row 2, cell 2</td> 
</tr> 
</table> 
1

您對所有使用class代替了相同Id。一個id必須是唯一的,你不能多次使用它。但是我們可以使用一個class來處理多個元素。

閱讀本documentation

$(".alertShow").click(function(){ 
     showAlertBox(); 
    }); 

<tr> 
<td class="alertShow">row 1, cell 1</td> 
<td class="alertShow">row 1, cell 2</td> 
</tr> 
<tr> 
<td class="alertShow">row 2, cell 1</td> 
<td class="alertShow">row 2, cell 2</td> 
</tr> 

Demo

1

您可以使用此代碼td無需使用classid

$(document).ready(function(){ 
    function showAlertBox(){ 
    $("#alert").css("display","inherit"); 
    $("#content").addClass("back"); 
    } 
    function removeAlertBox(){ 
     $("#alert").css("display","none"); 
     $("#content").removeClass("back");   
    } 

    $("#alertClose").click(function(){ 
     removeAlertBox(); 
    }); 
    $("table tr td").click(function(){ 
     showAlertBox(); 
    }); 
}); 

demo

1

你要學的最重要的事情是一個叫做事件委託的概念。 Read this post, it's very enlightening

當您閱讀帖子和關於該主題的一些信息時,答案顯而易見:只需將一個事件偵聽器附加到父節點,即可解決您的小問題。這是你的腳本: http://jsfiddle.net/stanislav_kay/xGdZJ/9/

<div id="content"> 
    <table border="1" id="alertShow"> 
    <tr> 
    <td id=11>row 1, cell 1</td> 
    <td id=12>row 1, cell 2</td> 
    </tr> 
    <tr> 
    <td id=21>row 2, cell 1</td> 
    <td id=22>row 2, cell 2</td> 
    </tr> 
    </table>