简体   繁体   中英

JavaScript function with parameters in HTML?

I want something like this:

function goTo (String string)
{
    window.location.href = string;
}

and access it with button click.. like:

 <button class="button" onClick="home(" My target url/file directory ")">Test</button> 

Is it possible?

您不能在双引号内使用双引号,而应使用单引号:

<button class="button" onClick="home(' My target url/file directory ')">Test</button>

You're on the right path:

 function goTo(url) { window.location.href = url; } 
 <button onClick="goTo('http://www.stackoverflow.com')">Test</button> 

yes, just that you need to tweak your code a little bit, fiddle

Function arguments doesn't need a type

function goTo ( string)
{
    window.location.href = string;
}

Finally, you need to escape inner double quotes

<button class="button" onClick="goTo ('My target url/file directory')">Test</button>

Okay so I got it working this way:

function locationUrl (string) {
    window.location.href = string;
}

 <button class="button" onClick="locationUrl(&quot;#&quot;)">Test</button> 

Thanks to you all!

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