저는 자바 스크립트를 처음 사용합니다. 나는 코드를 연습하고 있습니다. 머리 부분에 코드를 넣으면, 요소 null을 얻습니다. 그리고 body 안에 넣을 때, 그러나 요소 앞에 넣으면 null이됩니다. 그러나 body 안에 넣으면 요소 뒤에 그럼 나는 요소를 얻는다. 처음 두 사건의 경우 왜 내가 널리게되는지 묻고 싶습니다. 여기에 내 코드언제 자바 스크립트를 html로 넣을지
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="js/attributes.js"></script> // null
</head>
<body>
<script type="text/javascript" src="js/attributes.js"></script> // null
<a id="braingialink"
onclick="return showAttributes();"
href="http://www.braingia.org" >Steve Suehring's Web Site
</a>
<script type="text/javascript" src="js/attributes.js"></script> // ok
</body>
다음
가 요소 뒤에 <script type="text/javascript" src="js/attributes.js"></script>
을 배치 내 자바 스크립트
또한var a1 = document.getElementById("braingialink"); //get null in first two cases
window.alert(a1.getAttribute("href"));
a1.setAttribute("href", "www.google.com");
window.alert(a1.getAttribute("href"));
function showAttributes() {
var e = document.getElementById("braingialink");
var elementList = "";
for (var element in e) {
/**
* Sometimes, especially when first programming with JavaScript, you might not know what
* attributes are available for a given element. But you don’t have to worry about that, because
* of a loop that calls the getAttribute() method.
*/
var attrib = e.getAttribute(element);
elementList = elementList + element + ": " + attrib + "\n";
} //end of for()
alert(elementList);
} //end of function showAttributes
그리고 말해,이다, 내가 쓰기와 동일 스크립트 태그의 스크립트 (예 :
)<a href="http://www.braingia.org" id="braingialink">Steve Suehring's Web Site</a>
<script type="text/javascript">
var a1 = document.getElementById("braingialink");
alert(a1.getAttribute("href"));
a1.setAttribute("href","http://www.microsoft.com");
alert(a1.getAttribute("href"));
</script>
둘 다 같은 의미입니까?
감사
'
'을 사용할 때 묻고 싶습니다. 우리가'window.onload = someFunction() {...};'라고 쓰는 것과 같다. .js 파일에 간단한 함수를 쓰고, function someFunction() {..}을 쓰고, HTML에''줄을 사용하면, 다음과 같이 나타납니다. 내 .js 파일을 head 섹션에 넣고 .js에'window.onload = someFunction() {...};'이라고 씁니다. 둘 다 같습니까? – Basit거의 같습니다. '
html의 속성으로 설정하는 것은'window.onload = function() {something}'을 말하는 것과 같습니다. 즉, 속성에 넣은 코드는 함수는 일종의 함축적 인 함수를 가지고 있습니다. 많은 사람들은 자바 스크립트를 html로 혼합하지 않으려 고합니다. 유지하는 것이 더 어려울 수 있기 때문입니다. 참고 : html 속성에 설정된 JavaScript를 따옴표로 묶어야합니다. – nnnnnn