如何向 Javascript 添加条件语句(使用元素 ID 作为条件)?
我再次向 StackOverflow 的优秀用户提出另一个基本问题。我是客户端编程的新手,尽管这是我所知道的其他语言中相当基本的示例,但我不确定此处执行此操作的正确语法(如果已实现)。
这是我当前的代码。作为参考,可以在 http://paysonfirst assembly.com/ 找到该页面。但是,我还没有上传最新版本,并且生产服务器上尚不存在以下功能。
$(function () {
var $subnavContainer = $(".subwrapperBlue");
$(".navElements").click(function () {
$subnavContainer.show("slow");
});
这是我最近更新的代码。单击后该 div 不会重新出现,但会弹出警告框。
var $subnavContainer = $(".subwrapperBlue");
$(function () {
$(".navElements").click(function () {
switch ($(this).index()) {
case 0:
$subnavContainer.html("some html");
break;
case 1:
$subnavContainer.html("some more html");
break;
case 2:
$subnavContainer.html("some other html");
break;
case 3:
$subnavContainer.html("the final html");
break;
}
$subnavContainer.show("slow");
alert("this works");
});
Again, I have another basic question for the wonderful users here at StackOverflow. I am new to client-side programming and although this is a fairly basic example in other languages I know, I am unsure of the proper syntax of doing so here (if it has been implemented).
Here is my current code. The page, for reference, can be found at http://paysonfirstassembly.com/. However, I have not uploaded the most recent version and the function below does not exist on the production server (yet).
$(function () {
var $subnavContainer = $(".subwrapperBlue");
$(".navElements").click(function () {
$subnavContainer.show("slow");
});
This is my most recently updated code. The div will not reappear after clicking, however, the alert box DOES pop up.
var $subnavContainer = $(".subwrapperBlue");
$(function () {
$(".navElements").click(function () {
switch ($(this).index()) {
case 0:
$subnavContainer.html("some html");
break;
case 1:
$subnavContainer.html("some more html");
break;
case 2:
$subnavContainer.html("some other html");
break;
case 3:
$subnavContainer.html("the final html");
break;
}
$subnavContainer.show("slow");
alert("this works");
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以检查元素的索引。它以
0
作为第一个,1
作为第二个,等等:$(this)
指的是被单击的元素。与其执行长
if {} else if {} ...
链,为什么不使用switch
呢?在我看来,它更加简洁,因为您可以内联break;
:You can check the index of the element. It starts with
0
as the first,1
as the second, etc.:$(this)
refers to the element which was clicked.Instead of doing a long
if {} else if {} ...
chain, why not use aswitch
? It's much neater IMO as you can inline thebreak;
:如果你的 HTML 看起来像这样
你可以简单地这样做
If you HTML looks like this
You can simply do this
这样您就可以访问 event.target
或者,使用
$(this)
来测试您单击的元素。这实际上取决于你从什么开始。That's so you can get access to the event.target
Alternately, use
$(this)
to test the element that you clicked on. It really just kind of depends on what you're starting with.已经有一些很好的答案,但另一种方法是采用两种方法
There are alreayd a few good answers but another way would be having two methods