簡體   English   中英

單擊動態生成的表中的一行時,選中其單選按鈕

[英]On click of a row in a dynamically generated table, get its radio button checked

在我的網頁上,我有一個按鈕,單擊該按鈕可動態生成表格。 表格的每一行都有一個單選按鈕。 現在,我試圖單擊該行時選中該行的相應單選按鈕。 這是HTML

Insert table here
<button name="myreq" id="myreq" class="homeButtons">My Requests</button>
<table class="newreqtable" id="myrequesttable"></table>

這是我要實現的JS。 我已經在“ jsarray”中手動添加了值,以簡化演奏。 http://jsfiddle.net/4MYGa/1/

$("#myreq")
.button()
.click(function () {

var jsarray = new Array();
jsarray.push("1");
jsarray.push("requestor1");
jsarray.push("approver1");
jsarray.push("pending");
jsarray.push("chrome");
jsarray.push("25");
jsarray.push("source1");
jsarray.push("dest1");
jsarray.push("2");
jsarray.push("requestor2");
jsarray.push("approver2");
jsarray.push("pending");
jsarray.push("firefox");
jsarray.push("25");
jsarray.push("source2");
jsarray.push("dest2");

var table = '<table>';
table += '<tr><th>Select</th><th>RequestID</th><th >Requester</th><th>Approver</th><th>Status</th><th>Product</th><th>Version</th><th>Source</th><th>Destination</th></tr>';

for (var j = 0; j < jsarray.length; j += 8) {
    table += '<tr><td><input type="radio" name="requestradio" id="rad' + j + '"></td><td>' + jsarray[j] + '</td><td>' + jsarray[j + 1] + '</td><td>' + jsarray[j + 2] + '</td><td>' + jsarray[j + 3] + '</td><td>' + jsarray[j + 4] + '</td><td>' + jsarray[j + 5] + '</td><td>' + jsarray[j + 6] + '</td><td>' + jsarray[j + 7] + '</td></tr>';
}
table += '</table>';
$("#myrequesttable").html(table);
});

$('#myrequesttable tr').click(function () {

$('#myrequesttable tr').removeClass("active");
$(this).addClass("active");
$(this).find('[name="requestradio"]').prop('checked', true);
});

任何關於我可能做錯事情的想法都將非常有幫助。 謝謝

dom准備就緒后,您需要初始化事件。

 $("#myrequesttable").html(table);
//bind event when dom is ready
$('#myrequesttable tr').click(function () {
$('#myrequesttable tr').removeClass("active");
$(this).addClass("active");
$(this).find('[name="requestradio"]').prop('checked', true);

工作小提琴

嘗試這個

$('body').on('click','#myrequesttable tr',function (){

    $('#myrequesttable tr').removeClass("active");
    $(this).addClass("active");
    $(this).find('[name="requestradio"]').prop('checked', true);
});

DEMO

更改您的點擊事件:

$('#myrequesttable tr').click(function () {

對此:

$('#myrequesttable').on('click', 'tr', function () {

演示小提琴

看到所有<tr/>s都是動態生成的,因此在頁面加載時不存在它們,解決此問題的方法是將事件委托給頁面dom中最接近的靜態父級,該父級是#myrequesttable表。 所以你必須委托這個。

盡管您可以委托$(document)本身,但是如果考慮到性能,則應避免使用它。

將代碼修改為以下內容:

// Cache $("#myrequesttable")
var $myrequesttable = $("#myrequesttable");
$myrequesttable
    .on("click", "tr", function () {
        // Cache $(this)
        var $this = $(this);
        $myrequesttable.find("tr").removeClass("active");
        $this.addClass("active");
        $this.find('input:radio[name="requestradio"]').prop('checked', true);
    });

暫無
暫無

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

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