我從使用JQuery從XML文件中提取數據創建HTML表格。這些數據將通過HTTP POST發佈到其他地方。JavaScript:將增加的數字添加到名稱attr
當XML包含多個項目(即歌曲)時,它會創建相應的HTML,但input
元素的name
屬性保持不變。
這是jQuery代碼:
<script type="text/javascript">
$(document).ready(function() {
$.get('test.xml', function(d){
$('body').append('<form id="myForm" action="http://myendpoint.xyz/test" method="post" target="_blank" />');
$('#myForm').append('<div id="mySongs" />');
$('#mySongs').append('<input type="submit" value="Submit">');
$(d).find('song').each(function() {
var $song = $(this);
var title = $song.find('title').text();
var artist = $song.find('artist').text();
var price = $song.find('price').text();
var currency = $song.find('currency').text();
var html = '<div id="mySongs"> <span id="title"><input type="text" name="title" value="' + title + '" /></span>';
html += '<span id="artist"><input type="text" name="artist" value="' + artist + '" /></span>';
html += '<span id="price"><input type="text" name="price" value="' + price + '" /></span>';
html += '<span id="currency"><input type="text" name="currency" value="' + currency + '" /></span>';
html += '</div>';
$('#mySongs').append($(html));
});
});
});
</script>
拉動XML數據和運行上面的代碼後產生的HTML代碼看起來目前是這樣的:
<form id="myForm" action="http://myendpoint.xyz/test" method="post" target="_blank">
<input type="submit" value="Submit">
<div id="mySongs">
<span id="title">
<input type="text" name="title" value="Song Number 1"></span>
<span id="artist">
<input type="text" name="artist" value="Artist Number 1"></span>
<span id="price">
<input type="text" name="price" value="25.00"></span>
<span id="currency">
<input type="text" name="currency" value="EUR"></span>
</div>
<div id="mySongs">
<span id="title">
<input type="text" name="title" value="Song Number 2"></span>
<span id="artist">
<input type="text" name="artist" value="Artist Number 2"></span>
<span id="price">
<input type="text" name="price" value="30.00"></span>
<span id="currency">
<input type="text" name="currency" value="USD"></span>
</div>
</form>
我想補充增加編號爲name
屬性,以便在拉出多個項目時,代碼將顯示相應的編號以識別它(例如:name="title[1]"
)。
我想的HTML看起來如下圖所示,而不是:
<form id="myForm" action="http://myendpoint.xyz/test" method="post" target="_blank">
<input type="submit" value="Submit">
<div id="mySongs">
<span id="title">
<input type="text" name="title[1]" value="Song Number 1"></span>
<span id="artist">
<input type="text" name="artist[1]" value="Artist Number 1"></span>
<span id="price">
<input type="text" name="price[1]" value="25.00"></span>
<span id="currency">
<input type="text" name="currency[1]" value="EUR"></span>
</div>
<div id="mySongs">
<span id="title">
<input type="text" name="title[2]" value="Song Number 2"></span>
<span id="artist">
<input type="text" name="artist[2]" value="Artist Number 2"></span>
<span id="price">
<input type="text" name="price[2]" value="30.00"></span>
<span id="currency">
<input type="text" name="currency[2]" value="USD"></span>
</div>
</form>
如何實現這一目標?任何建議非常感謝。
打我吧.... – mplungjan
@charlietfl工程就像一個魅力。感謝您的幫助! –