簡體   English   中英

jQuery無法從$(this)按鈕單擊獲取ID

[英]jQuery cannot get id from $(this) button click

我正在嘗試使用jQuerythis )來單擊按鈕的ID,並將該ID傳遞給函數以執行某些操作。 我有三個具有不同ID的按鈕,並希望在我正在學習時使用$(this) ,但是無論我嘗試哪種方式都無法使其正常工作,這是代碼

 <html> <title>QuizMaster</title> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="jquery-3.1.0.min.js"></script> <script> function player(x){ var player = x; console.log(player); } $(document).ready(function(){ $('#button').click(function(){ var x = $(this).id; player(x); }); }); </script> </head> <body> <form id='button'> <input type='button' id='reset' value='Reset'> <input type='button' id='player1' value='Player1'> <input type='button' id='player2' value='Player2'> </form> </body> <html> 

我認為您應該聽輸入元素而不是#button。 而且您應該使用.attr()獲得ID

$(document).ready(function(){
        $('#button input').click(function(){
            var x = $(this).attr("id");
            player(x);
        });
    });

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <html> <title>QuizMaster</title> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script> function player(x){ var player = x; console.log(player); } $(document).ready(function(){ $('input[type="button"]').click(function(){ var x = $(this).attr('id'); player(x); }); }); </script> </head> <body> <form id='button'> <input type='button' id='reset' value='Reset'> <input type='button' id='player1' value='Player1'> <input type='button' id='player2' value='Player2'> </form> </body> <html> 

你應該這樣使用

$(document).ready(function(){
        $('input[type=button]').click(function(){
            var x = $(this).attr('id')
player(x);
});
    });

也許像這樣:

  function player(x){ var player = x; console.log(player); } $(document).ready(function(){ $('#button :button').click(function(){ var x = $(this).attr('id'); player(x); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <form id="button"> <input type="button" id="eset" value="Reset"> <input type="button" id="player1" value="Player1"> <input type="button" id="player2" value="Player2"> </form> 

您可能僅引用event.target元素即可獲得ID 此外,您不需要將this關鍵字轉換為jQuery對象,然后應用.attr方法:簡寫形式是:this.id。

片段:

 $(document).ready(function(){ $('#button').on('click', function(e){ var x = e.target.id; console.log('button pressed is: ' + x); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form id='button'> <input type='button' id='reset' value='Reset'> <input type='button' id='player1' value='Player1'> <input type='button' id='player2' value='Player2'> </form> 

暫無
暫無

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

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