简体   繁体   中英

Incorrect JavaScript Parameters Syntax

I'm trying to use JavaScript parameters in a function, but I'm not writing the syntax correctly.

This function is supposed to revert information in objects with the aa tag into whatever is specified with ba.

function myFunction(aa, ba){
    document.getElementById(aa).innerHTML = ba;
}

<p id="demo">JavaScript can change HTML content.</p>

<button type="button" onclick="myFunction(demo, My First Javascript)">Click Me!</button>

Add single quotes around the inputs to your function:

Javascript:

function myFunction(aa, ba){
    document.getElementById(aa).innerHTML = ba;
}

html:

<p id="demo">JavaScript can change HTML content.</p>

<button type="button" onclick="myFunction('demo', 'My First Javascript')">Click Me!</button>

here's a link to a codepen.io demo: https://codepen.io/167141162/pen/Vrgvbg

Strings in JavaScript must be wrapped in either "" or '' . In your example, JavaScript will think that you are trying to pass a variable (or a function) called demo for the first argument, and the second one ( My First Javascript ) will throw a SyntaxError .

So, this will work:

 function myFunction(aa, ba){ document.getElementById(aa).innerHTML = ba; } 
 <p id="demo">JavaScript can change HTML content.</p> <button type="button" onclick="myFunction('demo', 'My First Javascript')">Click Me!</button> 

用单引号包装字符串参数

<button type="button" onclick="myFunction('demo', 'My First Javascript')">Click Me!</button>

您的参数<< demo >>必须是单引号,因为在js文件中,参数将其视为字符串<button type="button" onclick="myFunction('demo', 'My First Javascript')">Click Me!</button>

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