2 回答
TA貢獻1772條經驗 獲得超5個贊
以下兩種變體都對我有用:
$('#product-selection option[value="pd3"]').prop("selected", true)
$('#product-selection option[value="pd3"]').prop("selected", "selected")
確保在插入來自服務器的 HTML后運行此代碼:
$(document).ready(function() {
$.post('load.php', {
req: 'load_product'
}, function(data, status) {
$("#product-selection").empty().append(data);
// Selection code needs to go into this callback,
// which is executed after the response comes back.
$('#product-selection option[value="pd3"]').prop("selected", "selected")
});
// Selection code SHOULD NOT be here, because this is executed
// right after the POST request is made.
// When code at this place is executed, the response has most
// likely not come back yet.
});
TA貢獻1803條經驗 獲得超6個贊
請檢查一下。您可以設置動態值“pdvalue”。當頁面加載時你可以使用它。
var pdvalue = "pd2";
$(document).ready(function() {
$.post('load.php', {
req: 'load_product'
}, function(data, status) {
$("#product-selection").empty().append(data);
});
// $('#product-selection').val("pd3"); <-Refer to Item 5. Problem
});
(function setpd(){
$('#product-selection option[value="'+ pdvalue +'"]').prop("selected", true)
})(jQuery);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<select id="product-selection">
<option selected disabled></option>
<option value="pd1">Product One</option>
<option value="pd2">Product Two</option>
<option value="pd3">Product Three</option>
<option value="pd4">Product Four</option>
</select>
- 2 回答
- 0 關注
- 129 瀏覽
添加回答
舉報
