簡體   English   中英

如何將類作為參數來運行?

[英]How can I give a class as a parameter to function?

當我將值作為參數來運行時,

像這樣,

 <html> <head> <style rel="stylesheet"> .A { border: 1px solid red; background-color: white } </style> <script> function clicked(v) { console.log(v); } </script> </head> <body> <input type="button" class="A" value="1" onclick="clicked(value)"> </body> </html> 

它運作良好。

它顯示了我的價值。

但是,當我把課作為參數時,

像這樣,

 <html> <head> <style rel="stylesheet"> .A { border: 1px solid red; background-color: white } </style> <script> function clicked(c) { console.log(c); } </script> </head> <body> <input type="button" class="A" value="1" onclick="clicked(class)"> </body> </html> 

它給了我一個錯誤。

我想讓它顯示按鈕的類選項“A”。

我該怎么做?

嘗試使用Element.getAttribute()

getAttribute()返回元素上指定屬性的值。 如果給定的屬性不存在,則返回的值將為null"" (空字符串);

onclick="clicked(this.getAttribute('class'))"

 <html> <head> <style rel="stylesheet"> .A { border: 1px solid red; background-color: white } </style> <script> function clicked(c) { console.log(c); } </script> </head> <body> <input type="button" class="A" value="1" onclick="clicked(this.getAttribute('class'))"> </body> </html> 

或者:使用Element.className

className獲取並設置指定元素的class屬性的值。

onclick="clicked(this.className)"

 <html> <head> <style rel="stylesheet"> .A { border: 1px solid red; background-color: white } </style> <script> function clicked(c) { console.log(c); } </script> </head> <body> <input type="button" class="A" value="1" onclick="clicked(this.className)"> </body> </html> 

或者:即使您可以傳遞對象,以便您可以根據需要訪問函數內的所有屬性:

onclick="clicked(this)"

 <html> <head> <style rel="stylesheet"> .A { border: 1px solid red; background-color: white } </style> <script> function clicked(c) { console.log(c.className); } </script> </head> <body> <input type="button" class="A" value="1" onclick="clicked(this)"> </body> </html> 

這是您的解決方案。 使用DOM元素className。

 <html> <head> <style rel="stylesheet"> .A { border: 1px solid red; background-color: white } </style> <script> function clicked(c) { console.log(c); } </script> </head> <body> <input type="button" class="A" value="1" onclick="clicked(this.className)"> </body> </html> 

你可以通過this給函數,然后該函數將有機會獲得所有的input元素屬性,其中之一是className ,但你也可以在訪問任何其他屬性,不改變調用機制

 <html> <head> <style rel="stylesheet"> .A { border: 1px solid red; background-color: white } </style> <script> function clicked(v) { console.log(v.className,v.value,v.type); } </script> </head> <body> <input type="button" class="A" value="1" onclick="clicked(this)"> </body> </html> 

暫無
暫無

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

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