首先,我認爲如果您需要稍後更新服務器數據,那麼請求帶有ajax請求的表數據作爲來自服務器的json數據會更好。
無論如何,用於獲取點擊一行,您還可以使用下面的腳本:
$('.selectionForm').on('change', 'input[type="radio"]',
function(event) {
console.log('changed radio', $(this).attr('name'), $(this).val(), $(this).parent().find('span'));
$(this).parent().find('span').text($(this).val());
});
它上升的DOM的點擊單選按鈕的父母,然後用找你再次下降到該行的跨度。
它使用事件委託,因爲這是從ajax請求動態添加內容所需的。這對PHP添加的內容不是必需的。
請參閱下面的演示,並在jsfiddle。
Handlebars.registerHelper('isChecked', function(input, options) {
//console.log(input, this);
//console.log(this, this.value, input);
return this.value === input? 'checked': '';
});
var $out = $('#out'),
rowTmpl = $("#row-template").html(),
template = Handlebars.compile(rowTmpl);
$.ajax({
url: 'http://www.mocky.io/v2/556d9fd9e822500114253f39',
jsonp: 'callback',
dataType: "jsonp",
success: function(response) {
console.log(response);
$.each(response, function(index, data) {
//console.log(data);
$out.append(template(data));
});
}
});
$('.selectionForm').on('change', 'input[type="radio"]', function(event) {
console.log('changed radio', $(this).attr('name'), $(this).val(), $(this).parent().find('span'));
$(this).parent().find('span').text($(this).val());
});
//$out.html(JSON.stringify(dataArray));
ul {
list-style-type: none;
}
li {
border-bottom: 1px solid gray;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/3.0.3/handlebars.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>form loaded with ajax request:</h1>
<p>table generated with javascript</p>
<form class="selectionForm">
<ul id="out"></ul>
<!--<ul>
<li>
<input type="radio" name="row0" value="0"/>0
<input type="radio" checked="" name="row0" value="1"/>1
<span class="badge">1</span>
</li>
<li>
<input type="radio" name="row1" value="0"/>0
<input type="radio" checked="" name="row1" value="1"/>1
<span class="badge">1</span>
</li>
</ul>-->
</form>
<script id="row-template" type="text/x-handlebars-template">
<li>
<input type="radio" value="0" name="row{{id}}" {{isChecked 0 }}/>0
<input type="radio" value="1" name="row{{id}}" {{isChecked 1 }}/>1
<span class="badge">{{value}}</span>
</li>
</script>
<h1>form generated with server side script</h1>
<form class="selectionForm">
<ul>
<li>
<input type="radio" name="row0" value="0"/>0
<input type="radio" checked="" name="row0" value="1"/>1
<span class="badge">1</span>
</li>
<li>
<input type="radio" name="row1" value="0"/>0
<input type="radio" checked="" name="row1" value="1"/>1
<span class="badge">1</span>
</li>
</ul>
</form>
可以顯示HTML輸出的PHP已被執行之後,謝謝。 – NewToJS
http://jsfiddle.net/8ek2x58o/即表格中一行的輸出。 – Thug
你有沒有實現任何jQuery代碼? –