亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

呈現多個下拉列表時訪問 JS 中的 boostrap 下拉值

呈現多個下拉列表時訪問 JS 中的 boostrap 下拉值

aluckdog 2023-04-27 17:23:52
在 javascript 中,我有多個行從 Firebase/Firestore 集合呈現到 DOM。在每一行中,都會創建一個始終具有相同選擇選項(.a 元素)的 Bootstrap 下拉列表。每行 div 的 id 屬性是根據 Firestore doc.id 動態設置的。當用戶在下拉列表中單擊它時,我想從一個特定行的下拉列表中獲取選定的值。這是我的代碼:    //get Firestore collection    db.collection('collection1').get().then(snapshot => {    snapshot.docs.forEach(doc => {      //create row to be rendered...      let row = document.createElement('div');      let container = document.getElementById('myContainer');      //...append it to the container element      container.appendChild(row);      //set row id to the doc.id for future access      row.setAttribute('id', doc.id);      //bootstrap dropdown rendered here      document.getElementById(doc.id).innerHTML =        '<span class="font-weight-bolder border rounded p-2 dropdown-toggle" id="selectStatus' +doc.id+ ' "  data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">' + doc.data().status+ '</span>'        +        '<div class="dropdown-menu" aria-labelledby="selectStatus' + doc.id + '">' +        '    <a class="dropdown-item" href="#">Action</a>' +        '    <a class="dropdown-item" href="#">Another action</a>' +        '    <a class="dropdown-item" href="#">Something else here</a>' +        '  </div>';       });     });我試過這個:$('#someId a').on('click', function(){$('#someOtherId').val($(this).html());});和其他帖子中的其他解決方案,但據我了解,它們總是指一個單一的 Dropdown 元素。在我的例子中,有多行每行都有一個下拉元素,當然每一行的下拉列表 id 都會發生變化。任何提示都會很有幫助!
查看完整描述

1 回答

?
三國紛爭

TA貢獻1804條經驗 獲得超7個贊

您可以在處理點擊事件時忽略 ID 并觀察超鏈接類:


使用 jQuery:


$('a.dropdown-item').on('click', function(e) { 

    // You don't want to navigate away from this page I suppose?

    e.preventDefault();


    $('#someOtherId').val($(this).text());

});

使用普通 JavaScript (ES6):


const elements = document.getElementsByClassName("dropdown-item");


const myHandler = (e) => {

    // You don't want to navigate away from this page I suppose?

    e.preventDefault();


    const myElement = document.getElementById("someOtherId");

    

    myElement.value = this.text;

};


Array.from(elements).forEach(function(element) {

    element.addEventListener('click', myHandler);

});


查看完整回答
反對 回復 2023-04-27
  • 1 回答
  • 0 關注
  • 136 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號