简体   繁体   中英

jquery “if” something and “else” something

I am just curious how would anyone make this. I am trying to figure out with lack of knowledge and of course I cannot make it.

So it would be something like...

If in jquery there is declared onClick function something like "firstGateway" and "secondGateway" how can I add what if there is first and what if its second.

I can't even explain well.

But let me try.

<a onClick="firstGateway">YES FIRST!</a>

That would be html piece and jquery would need to run following:

<script type="text/javascript" src="http://fileice.net/gateway/mygate.php?id=492b542f45684b42"></script>
onClick=startGateway('123456');

and if it would be in html like this:

<a onClick="secondGateway">YES SECOND!</a>

Then jquery would run following:

<script type="text/javascript" src="http://fileice.net/gateway/mygate.php?id=4465766c4278366467523838"></script>
onClick=startGateway('654321');

Hope you understand me. I will still try to make it work but I do not think I will be able to succeed.

$('a').click(function(e){
    if (e.target.innerHTML == "something")
        //fooo
    else
        // Bar
});

You can check anything you want inside the callback. e.target is the anchor that was clicked.

if (e.target.id == "someId")
if ($(e.target).hasClass('fooClass'))

With your current code, if someone clicks on the link nothing happens. Let's fix that first of all:

This:

<a onClick="firstGateway">YES FIRST!</a>

Should be this:

<a onClick="firstGateway()">YES FIRST!</a>

If you want to execute the function firstGateway() whenever the user clicks that link. However, this is still not the best way and I'm going to show you a better way below. (Note that this better way is also needed for my final solution).

Now we turn this into:

<a id='gateway1'>YES FIRST!</a>

No longer do we define the event in the HTML, instead we do so in our javascript using jQuery:

$(document).ready(function ()
{
    $('a#gateway1').click = firstGateway; // Do note: this time around there are 
                                          // no brackets
}

Using this, you can now do several things. First, you could do this:

$('a#gateway1').click();

It simulates a click on the link, which I believe does the thing you wanted to do.

However, in order to write your code, you have made sure that you knew what function you were connecting to it in your javascript, so you might not even need such a solution anymore as you should be able to do this:

$(document).ready(function ()
{
    $('a#gateway1').click = firstGateway; // Do note: this time around there are 
                                          // no brackets

    firstGateway();
}

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