2013-11-20 4 views
0

На моей веб-странице есть кнопка, клика которой динамически генерирует таблицу. Каждая строка таблицы имеет переключатель. Теперь я пытаюсь установить соответствующий переключатель в строке, когда я нажимаю на эту строку. Вот 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); 
}); 

Любые мысли относительно того, что я могу делать неправильно было бы очень полезно. Спасибо

ответ

2

Нужно инициализировать событие, когда 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); 

Working Fiddle

1

Попробуйте этот

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

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

DEMO

1

изменение ваше событие щелчка:

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

к этому:

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

Demo Fiddle

Смотрите ваш все <tr/>s генерируется динамически, так что они не существуют, когда страница была загружена, решение этой проблемы заключается в делегировании события в ближайшем статическом родительский элемент в вашей домашней странице, то есть #myrequesttable стол. поэтому вы должны делегировать это.

Хотя вы можете делегировать только $(document), но если это касается производительности, его следует избегать.

1

Изменить код будет следующим:

// 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); 
    }); 
Смежные вопросы