document.getElementById("idName");
のように私自身の機能をどうすれば.innerHTML
にすることができますか?たとえば、document.getElementById("idName").myFunction;
のようになります。ここでオブジェクトJavaScript用の関数を作成するにはどうすればよいですか?
答えて
HTMLElementプロトタイプを変更する必要があります。
document.getElementByIdはHTMLElementオブジェクトを返しますが、一般にネイティブオブジェクトは変更される可能性があるため、ネイティブオブジェクトを変更することは悪い習慣と考えられ、別のブラウザで問題が発生する可能性があります。また、さまざまな要素に対して異なる処理が必要な場合もあります。
(function(proto) {
// HTMLelement prototype is passed into the closure
// set your method if it's not set on the prototype
proto.myFunction = proto.myFunction || function() {
// this === element that method was run on
console.log('myFunction', this.textContent)
}
})(HTMLElement.prototype)
var element = document.getElementById('element')
element.myFunction()
<div id="element">this is my element</div>
あなたは今までの方法を持っているしたい場合。私は、jQueryを使用し、新しい動作をアタッチするためのシンプルなプラグインを作成することをお勧めします。また、要素のコレクションを扱うことができ、ヘルパ関数としてjQuery APIを利用できるという利点も得られます。
!(function($){
// jQuery is passed into the closure
// $.fn === $.prototype === jQuery.prototype
$.fn.myFunction = function(){
// this === the element that the method was run on
console.log($(this).text())
}
})(jQuery)
var $element = $('#element')
$element.myFunction()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="element">this is my $element</div>
は、あなたがこのついて行くだろうかです:
文字列などのオブジェクトのための新しい方法を作成するには、単にString.prototype.MethodName = function(args) { code }
を行うことができます。ここで
は一例です。この例では
String.prototype.replaceAll = function(a, b) {
var regExp
regExp = new RegExp(a, "ig")
return this.replace(regExp, b)
}
g = "Hello null"
console.log(g)
g = g.replaceAll("null", "World!")
console.log(g)
、我々はreplaceAll
機能を作成しました。これは特定の単語またはフレーズと を置き換えるために使用されます。これを行うと、String
のreplaceAll関数を呼び出すことができます。
希望すると便利です。
ああ、皆さんに知ってもらうために、**有効なJavascript **のためにセミコロンは必要ありません。 – Superwhiskers
あなたは '(){...}(){...}' object.Prototype.methodName =機能を行う ''または直接object.methodName =機能を追加することができます。これは複製です。下のリンクを参照してください。 –
'.innerHTML'は関数ではありません。 *すべての* DOM要素に関数を追加する方法を尋ねていますので、 'document.getElementById(" anyElementId ")。myFunction()'と言うことができますか?または、特定のDOM要素に対してのみ関数を使用できるようにしますか? – nnnnnn
あなたは* property *を意味しますか? – Li357