开发者

How to attach click event at runtime when i have all ids in an array that gets populated when document is ready?

I have the following code,

    <script type="text/javascript">
        $(document).ready(function () {
            var dataAnalysisDataFileTableIDs = $("#dataAnalysisDataFileTable tr[id]").map(function () { return this.id; }).get();

            //for(var key in dataAnalysisDataFileTableIDs) {
            //    var id = "#" + dataAnalysisDataFileTableIDs[key];
            //    $(id).click(function () {
            //        alert("[" + index + "][" + value + "]");
            //    });
            //}
            //$.each(dataAnalysisDataFileTableIDs, function (index, value) {
            //    var id = "#" + dataAnalysisDataFileTableIDs[key];
            //    $(id).click(function () {
            //        alert("[" + index + "][" + value + "]");
开发者_StackOverflow社区            //    });
            //});
            $("#dataAnalysisDataFileTable tr[id]").each(function (i, elem) {
                $(elem).click(function () { alert("[" + i + "][" + this.id + "]"); });
            });
            $("#aaa").click(function () {
                alert("meow");
            });
        });
    </script>

and it doesn't work i also tried the one in the comments section which does the same as "for in" it doen't work but when i attach click to the id #aaa it works fine how do i approach this problem when i have all the ids in the array and i want to be able to attach events to them?


How about just using each ? Like so:

<html>
<head><script type="text/javascript" src="http://code.jquery.com/jquery-1.6.4.min.js"></script></head>
<body>
<table id="dataAnalysisDataFileTable">
<tr id="foo"><td>foo</td></tr>
<tr id="bar"><td>bar</td></tr>
</table>
<script type="text/javascript">
  $(document).ready(function () {
    $("#dataAnalysisDataFileTable tr[id]").each(function(i, elem) {
      $(elem).click(function() { alert("[" + i + "][" + this.id + "]") } );
    });
  });
</script>
</body>
</html>


I've patched the possible errors. I cannot resolve the value variable though.

    for(var index=0, length=dataAnalysisFileTableIDs.length; index++) {
        var key = dataAnalysisFileTableIDs[index];
        var id = "#" + dataAnalysisFileTableIDs[key];
        $(id).click(function () {
            /* Value ? It's not defined*/
            alert("[" + index + "][" + /*value +*/ "]");
        });
    }

dataAnalysisFileTableIDs is an array. To loop through an array, you have to use the for ( init_index ; condition ; increment ) loop. The key can be obtained through name_of_array[index].

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜