問題就像這樣簡單 - 是否可以爲標準js對象創建用戶定義的方法,如val
方法input
?也就是說,要做到水木清華這樣的:JS - 爲自定義js對象創建用戶定義函數
function my_new_method()
{
...
}
...
alert($('td input').my_new_method())
問題就像這樣簡單 - 是否可以爲標準js對象創建用戶定義的方法,如val
方法input
?也就是說,要做到水木清華這樣的:JS - 爲自定義js對象創建用戶定義函數
function my_new_method()
{
...
}
...
alert($('td input').my_new_method())
自認爲是看起來像jQuery(不香草/標準JavaScript),你可以簡單地使用$.fn.my_new_method = // your function
你可以讀了如何在這裏創建一個jQuery插件:https://learn.jquery.com/plugins/basic-plugin-creation/
您可以使用Object prototype。
Object.prototype.my_new_method = function() {
console.log(this.val());
}
$("#test").my_new_method();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' value='abc' id="test">
檢查這一個[鏈接](http://stackoverflow.com/questions/9354298/how-do-i-write-an-extension-method-in-javascript) – vikscool
查看[Javascript Prototype](http://stackoverflow.com/questions/572897/how-does-javascript-prototype-work)和[MDN文章](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype)可能也有幫助。 – Tigger
你應該嘗試閱讀關於jquery插件,這裏有一個示例:https://learn.jquery.com/plugins/basic-plugin-creation/ – Mayday