[英]Generate "selected" html tag in a listbox
我有一個名為“Bookly”的 Wordpress 插件。 它生成一個帶有一些值的列表框。 我需要通過 Jquery 獲取選定的值,但是當我選擇一個值時,這個選擇框不會生成 selected="selected" 。
我怎樣才能做到這一點?
PHP文件:
<select id="service" class="bookly-select-mobile bookly-js-select-service">
<option value=""><?php echo esc_html( Common::getTranslatedOption( 'bookly_l10n_option_service' ) ) ?></option>
</select>
HTML 渲染:
<select id="service" class="bookly-select-mobile bookly-js-select-service">
<option value="">Choose a service</option>
<option value="1">Service 1</option>
<option value="2">Service 2</option>
</select>
我需要的 :
<select id="service" class="bookly-select-mobile bookly-js-select-service">
<option value="">Choose a service</option>
<option value="1" selected="selected">Service 1</option>
<option value="2">Service 2</option>
</select>
const service = document.getElementById('service');
service.addEventListener('click', (e) => {
// wipe previous 'selected' elements
Array.from(e.target.querySelectorAll('option')).forEach((option) => {
option.removeAttribute('selected');
});
e.target.querySelector(`option[value="${e.target.value}"`).setAttribute('selected', 'selected');
});
這是一個JSFiddle ,您可以在其中看到它的運行情況。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.