この例では、制御したい要素への参照がある場合を示しています。すでに要素への参照を持っている場合は、それへの参照を取得するためにdocument.getElementById
を使用する理由は、(あなたが既に持っている)が存在しない:
<span id="mySpan" onclick="test(this);">TEST</span>
<script type="text/javascript">
function test(el) {
// el is a reference to an element, you can use it directly
el.style.display = 'none';
// to demonstrate that the element you retrieve from gEBI
// with el.id is the same as your original reference
var elAgain = document.getElementById(el.id);
alert(elAgain === el); // "true"
}
</script>
したいときにdocument.getElementById
を使用する場合があります場所です(これまでであれば)ほとんどありませんことを、次のような何か理由
が
<span id="mySpan" onclick="test(this, 'myDiv');">TEST</span>
<div id="myDiv" style="display:none;">DIV REVEALED</div>
<script type="text/javascript">
function test(el, otherElId) {
// el is a reference to an element, you can use it directly
el.style.display = 'none';
// otherElId is a string containing the id of
// the element you want to control
var theDiv = document.getElementById(otherElId);
theDiv.style.display = '';
}
</script>
注:
<span id="mySpan" onclick="test('mySpan');">TEST</span>
<script type="text/javascript">
function test(theElId) {
var el = document.getElementById(theElId);
el.style.display = 'none';
}
</script>
をすでに参照を持っていないためにどの他の要素を制御します
関数が要素イベントから起動されている場合は、イベントが発生している要素のIDを渡すのではなく、this
(最初の例のとおり)を渡すことができます。
お返事いただきありがとうございます。今後のことを教えていただきありがとうございます。 – CindyH