<script type="text/javascript">
var count = 0;
var max = 5;
$(function(){
$('p#add_field').click(function(){
count += 1;
if(count >= max)
return;
$('#container2').append(
'<strong>Golf Course ' + count + '</strong>   '
+'<select id="field_' + count + '" name="fields[]">' + "<?php foreach ( $courses as $course ) { $name = $course->coursename; ?>"+"<?php echo '<option value=\''.htmlspecialchars($name).'\'>'.$name.'</option>'; ?>"+"<?php } ?>"+'</select><br />')
});
});
</script>
尽管如此,您的代码还是相当难以维护 - 将 PHP 与 JS 分开。
编辑:也考虑这个解决方案:
// this way you provide a JSON serialization of your server data
<script type="application/json" id="select-data">
<?php echo json_encode($courses); ?>
</script>
// this is pure js: doesn't care where the data comes from
<script type="text/javascript">
$(function(){
// we parse the JSON string, and get a Javascript array
var selectData = $.parseJSON( $("#select-data").text() );
var count = 0;
var max = 5; // pick the number you want here
// we create a new select, based on the count parameter
function makeSelect(count){
var $select = $('<select>', { id : 'field_' + count, name : "fields[]" });
$.each(selectData, function(){
$select.append(
$('<option>', { value : this.name, text : this.name })
)
})
return $select;
}
$('p#add_field').click(function(){
count += 1;
if(count >= max)
return;
$('#container2').append($('<strong>', { text : "Golf Course " + count }));
$('#container2').append(makeSelect(count));
});
});
</script>