繁体   English   中英

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

[英]jquery “if” something and “else” something

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

所以它会像......

如果在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');

希望你能理解我。 我仍然会尝试让它发挥作用,但我认为我不会成功。

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

你可以在回调中检查你想要的任何东西。 e.target是被点击的锚点。

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

使用您当前的代码,如果有人点击链接,则没有任何反应。 让我们首先解决这个问题:

这个:

<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中连接到它的功能,所以您甚至可能不再需要这样的解决方案,因为您应该能够这样做:

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

    firstGateway();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM