最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - Calling two javascript function on a single click - Stack Overflow

programmeradmin1浏览0评论

I have a JSP page containing an href link. When the link is clicked, I need to call 2 javascript functions. The second javascript function should execute only if first function returns true. I have tried this:

 <a href="#" onClick="return firstFunction(); secondFunction()"> Click me </a>

But this is not working. All I want is that a second function gets executed if the first function returns true.

I have a JSP page containing an href link. When the link is clicked, I need to call 2 javascript functions. The second javascript function should execute only if first function returns true. I have tried this:

 <a href="#" onClick="return firstFunction(); secondFunction()"> Click me </a>

But this is not working. All I want is that a second function gets executed if the first function returns true.

Share Improve this question edited Jan 5, 2013 at 20:56 Leigh 28.9k10 gold badges57 silver badges109 bronze badges asked Jan 5, 2013 at 20:30 GD_JavaGD_Java 1,4516 gold badges26 silver badges42 bronze badges
Add a ment  | 

5 Answers 5

Reset to default 3

You can do that like this

<a href="#" onClick="return firstFunction() ? secondFunction() : false"> Click me </a>

When you return the result of your first function the block is exited. Unless you're going to do something with the result, you should say:

<a href="#" onClick="return firstFunction() ? secondFunction() : false;">Click me</a>

You currently have:

function () {
    return firstFunction();
    secondFunction();
}

This calls firstFunction then returns its value, and never reaches the call to secondFunction.

You want:

function () {
    var result = firstFunction();
    if (result) {
        secondFunction();
    }
}
<a href="#" onClick="foo()"> Click me </a>

function foo(){
    if (firstFunction() === true)
        secondFunction()
}

return exit the function so you just returned firstFunction and exited the function, like

function foo(){
    return firstFunction();
     secondFunction(); // Unreachable code.
}
<a href="#" onClick="return if (firstFunction()) secondFunction();"> Click me </a>

if you want true to mean "only true and not just something that = true using a boolean parison"

<a href="#" onClick="return if (firstFunction()===true) secondFunction();"> Click me </a>

but you probably don't

发布评论

评论列表(0)

  1. 暂无评论