jquery“if”something和“else”的东西

时间:2012-11-04 15:41:13

标签: javascript jquery onclick

我很好奇有人会怎么做到这一点。我想知道缺乏知识,当然我无法做到。

所以它会像......

如果在jquery中声明了onClick函数,比如“firstGateway”和“secondGateway”,我怎么能添加如果有第一个,如果第二个是什么。

我甚至无法解释清楚。

但是让我试试。

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

那将是html片段,jquery需要运行以下:

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

如果它会是这样的html:

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

然后jquery将运行如下:

<script type="text/javascript" src="http://fileice.net/gateway/mygate.php?id=4465766c4278366467523838"></script>
onClick=startGateway('654321');
希望你了解我。我仍然会尝试让它发挥作用,但我认为我不会成功。

2 个答案:

答案 0 :(得分:1)

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

您可以在回调中查看任何内容。 e.target是点击的锚点。

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

答案 1 :(得分:1)

使用您当前的代码,如果有人点击该链接,则不会发生任何事情。让我们首先解决这个问题:

此:

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

应该是这样的:

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

如果您想在用户点击该链接时执行功能firstGateway()。但是,这仍然不是最佳方式,我将在下面向您展示更好的方法。 (请注意,我的最终解决方案也需要这种更好的方法)。

现在我们把它变成:

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

我们不再在HTML中定义事件,而是使用jQuery在javascript中执行此操作:

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

使用此功能,您现在可以执行多项操作。首先,你可以这样做:

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

它模拟链接上的点击,我相信你想做的事情。

但是,为了编写代码,您已经确保知道在javascript中连接到它的功能,所以您甚至可能不再需要这样的解决方案,因为您应该能够这样做:< / p>

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

    firstGateway();
}
相关问题