簡體   English   中英

根據用戶在jQuery中的輸入從數組中獲取價值

[英]Get value from array based on user input in jQuery

我有一個帶有字母的數組,每個字母都有一個URL。 我也有一個按鈕列表,每個按鈕對應於一個字母。

我想根據用戶單擊哪個按鈕從數組(URL)中檢索值,用戶可以單擊多個按鈕。

因此,如果用戶單擊按鈕“ C”,我想從數組中檢索與字母“ C”關聯的URL。

我能夠遍歷#letters元素的子級並獲取每個按鈕的id 我曾想過以某種方式將其與陣列進行比較,但是我一路迷路了。

我真的沒有解決方案。

的HTML

<div class="col-md-12" id="letters">
   <a href="#" class="btn btn-primary" id="A">A</a>
   <a href="#" class="btn btn-primary" id="B">B</a>
   <a href="#" class="btn btn-primary" id="C">C</a>
</div>

Java腳本

$(function() {
    let array = {
        'A' : 'http://example.com/A.png',
        'B' : 'http://example.com/B.png',
        'C' : 'http://example.com/C.png',
    };

    $.each(array, function(key, value) {
        console.log('Initializing...', key + ' => ' + value);
    });

    let letters = $('#letters');
    $.each(letters.children(), function(i) {
        console.log(letters.children()[i].id); // get value of id tag
    });
});

這是一個片段,我獲取了所有鏈接並在其上附加了click事件,該事件僅記錄鍵對應於clicked按鈕id的值

 (function(){ let array = { 'A' : 'http://example.com/A.png', 'B' : 'http://example.com/B.png', 'C' : 'http://example.com/C.png', }; const buttons = document.querySelectorAll('#letters a'); buttons.forEach(button => { button.addEventListener('click', (e) => console.log(array[e.target.id])); }); })(); 
 <div class="col-md-12" id="letters"> <a href="#" class="btn btn-primary" id="A">A</a> <a href="#" class="btn btn-primary" id="B">B</a> <a href="#" class="btn btn-primary" id="C">C</a> </div> 

使用data- *屬性並將事件偵聽器添加到您的信件中,單擊獲取被單擊的項目,然后使用.data()獲得信件。

 $(function() { let array = { 'A' : 'https://images.pexels.com/photos/67636/rose-blue-flower-rose-blooms-67636.jpeg?cs=srgb&dl=beauty-bloom-blue-67636.jpg&fm=jpg', 'B' : 'https://images.pexels.com/photos/1308881/pexels-photo-1308881.jpeg?cs=srgb&dl=ao-dai-beautiful-beauty-1308881.jpg&fm=jpg', 'C' : 'https://images.pexels.com/photos/237018/pexels-photo-237018.jpeg?cs=srgb&dl=asphalt-beauty-colorful-237018.jpg&fm=jpg', }; $('.btn-primary').on('click', function() { const letter = $(this).data('letter'); $('#demo').attr('src', array[letter]); }); }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="col-md-12" id="letters"> <a href="#" data-letter="A" class="btn btn-primary" id="A">A</a> <a href="#" data-letter="B" class="btn btn-primary" id="B">B</a> <a href="#" data-letter="C" class="btn btn-primary" id="C">C</a> </div> <img width="300" id="demo" src="" /> 

如果您打算將來增加更多內容,那么用HTML編寫鏈接是沒有意義的。 節省一些時間並動態生成它們。 下面提供了一個可重用的函數listLnx() ,它將從給定的幾乎無限數量的url列表中以HTML形式生成<a> 演示中評論了全部詳細信息。

 // An Array of Arrays each sub-array has a key/value pair let urls = [ ['A', 'https://example.com/'], ['B', 'https://stackoverflow.com'], ['D', 'https://stackoverflow.com/users/2813224/zer00ne'], ['C', 'https://css-tricks.com'], ]; /*** listLnx() 1st Param: [Array] (see above) 2nd Param: [String] (optional--default: "body") the tag in which the links will be nested within */ /* *A - Reference the parent tag *B - Instantiate Map Object from the array. Array is reversed because the links are prepended to parent *C - Iterate through map with a for...of loop. The entries() method returns an array of key/value pairs which is destructured for easy access *D - An <a> is created with .createElement() method. The remaining statements assemble each link with the following: 1. an #id 2. a [href] 3. text of #id and hostname 4. block level style 5. then prepended to parent tag */ const listLnx = (array, selector = `body`) => { let node = document.querySelector(selector); //A let map = new Map(array.reverse()); //B for (const [key, url] of map.entries()) { //C const a = document.createElement('a'); //D a.id = key; //1 a.href = url; //2 a.textContent = `${key} - ${a.hostname}`; //3 a.style.display = 'block'; //4 node.prepend(a); //5 } } listLnx(urls); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM