我有 4 个相邻的 div,每个都包含一个链接。我想动态切换“当前”的id,
例如。
<div name="1" id="current">
<a>
link
</a>
</div>
<div name="2">
<a>
link
</a>
</div>
<div name="3">
<a>
link
</a>
</div>
<div name="4">
<a>
link
</a>
</div>
单击链接时,如何动态更改哪个是当前链接?
Don't do this. Element IDs should not change based on the state of the web page. Use another attribute instead, like class="current"
.
If you're using jQuery, which I highly recommend, you can do this as follows:
$('div.tab a').click(function() {
$('div.tab').removeClass('current');
$(this).closest('div.tab').addClass('current');
return false;
});
To make this code work, you need to add class="tab"
to your <div>
elements. This is a good idea especially if you have other <div>
elements on the page. If you do this, the current tab would then have an attribute class="tab current"
. jQuery knows how to handle this properly.
Also, I would consider using the id
attribute instead of the name
attribute, and giving your <a>
tags a href
attribute so that browsers will show them as clickable elements. For example:
<div id="tab1" class="tab">
<a href="#">tab 1</a>
</div>
Here's an example of how to include this script (assuming that you have JQuery saved as a file jquery.js
in the same directory as the HTML page):
<!DOCTYPE html>
<html>
<head>
<title>Testing jQuery</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(function() {
$('div.tab a').click(function() {
$('div.tab').removeClass('current');
$(this).closest('div.tab').addClass('current');
return false;
});
});
</script>
</head>
<body>
<div id="tab1" class="tab current">
<a href="#">tab1 link</a>
</div>
<div id="tab2" class="tab">
<a href="#">tab2 link</a>
</div>
<div id="tab3" class="tab">
<a href="#">tab3 link</a>
</div>
<div id="tab4" class="tab">
<a href="#">tab4 link</a>
</div>
</body>
</html>
A couple of notes about that:
Really, it's better to put your site's JavaScript in a separate file and include it with <script type="text/javascript" src="filename.js"></script>
, but including it "inline" like I've done is fine for small projects or just playing around with stuff.
The $(function() { ... });
is shorthand for $(document).ready(function() { ... });
, which means the code inside that block will be executed as soon as the browser has finished loading the HTML document structure. For example, you don't want your JavaScript to execute before the browser has finished downloading the rest of the page.
您可以更改除 id 之外的所有内容!