简体   繁体   中英

Why won't my inline JavaScript function work?

What seems to be the problem? The code doesn't work, the text does not change.

 function translate() { document.getElementById("tex").innerHTML = "BLABLA"; } 
 <h1 align="center"><font size="100">What Is BLA: </font></h1> <p id ="tex"><font size="10">BLA</font></p> <button onclick="translate()">Translate</button> 

The problem is in some browsers, like Chrome, DOM elements have a translate property (MDN does not list Chrome as supporting this feature, but it does have the property). In the context of JavaScript event attributes, those properties shadow any globals of the same name.

If you check your developer console, you should see a message saying that translate is not a function because of this.

Uncaught TypeError: translate is not a function

If you change the name of the function, you will avoid this issue:

 function myTranslate() { document.getElementById("tex").innerHTML = "BLABLA"; } 
 <h1 align="center"><font size="100">What Is BLA: </font></h1> <p id ="tex"><font size="10">BLA</font></p> <button onclick="myTranslate()">Translate</button> 

Maybe also to note is that you are trying to set the innerHTML of the p element with the id tex . But the element has a child element in it. You can set the innerHTML property of that item.

document.getElementById("tex").childNodes[0].innerHTML = "BLABLA";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM