2013-10-22 82 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>