【问题标题】:sorting works manually but not with "onclick" functions手动排序,但不能使用“onclick”功能
【发布时间】:2020-07-18 11:58:56
【问题描述】:

我有一个名字列表,我想按他们有多少分来排序,默认设置为0,每次我按下一个按钮时,它都会为那个特定的名字添加一个点,但没有排名他们首先是,如果我在JS 列表中手动添加点它工作正常,但当我使用按钮时不行。这是我尝试过的:

 let characters = [
       {name: document.getElementById("name 1").textContent, points: 0},
       {name: document.getElementById("name 2").textContent, points: 0},
       {name: document.getElementById("name 3").textContent, points: 0}
    ];
        
    function choice (button) {
       const buttonCharacterObject = characters.find(obj => obj.name === button.textContent);
       buttonCharacterObject.points += 1;
       
       console.log(characters)
    }

    const ranking = characters.sort((a, b) => (a.points < b.points ? 1 : -1));
    
    console.log(ranking);
    <button id="name 1" onclick="choice(this)">John</button>
    <button id="name 2" onclick="choice(this)">Martin</button>
    <button id="name 3" onclick="choice(this)">Sam</button>


   

【问题讨论】:

    标签: javascript html arrays sorting


    【解决方案1】:

    只要把排名也放入函数中,控制台输出排名字符。

     let characters = [
           {name: document.getElementById("name 1").textContent, points: 0},
           {name: document.getElementById("name 2").textContent, points: 0},
           {name: document.getElementById("name 3").textContent, points: 0}
        ];
            
        function choice (button) {
           const buttonCharacterObject = characters.find(obj => obj.name === button.textContent);
           buttonCharacterObject.points += 1;
           
        const ranking = characters.sort((a, b) => (a.points < b.points ? 1 : -1));
        
        console.log(ranking);
        }
    
        
        <button id="name 1" onclick="choice(this)">John</button>
        <button id="name 2" onclick="choice(this)">Martin</button>
        <button id="name 3" onclick="choice(this)">Sam</button>
    
    
       

    【讨论】:

      【解决方案2】:

      积分增加后,需要在choice()方法中进行排序。

      尝试以下:

      function choice (button) {
         const buttonCharacterObject = characters.find(obj => obj.name === button.textContent);
         buttonCharacterObject.points += 1;
      
         characters.sort((a, b) => (a.points < b.points ? 1 : -1));
      
         console.log(characters)
      }
      

      【讨论】:

      • 试过了,但是 console.log(ranking);也需要在函数中,谢谢您的帮助
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-03
      • 1970-01-01
      相关资源
      最近更新 更多