我想通过<a>
标签创建10个体内链接。在演示中,您可以看到代码太长,只有3个链接,我确信有一种方法可以改进此代码。
那么,我怎么知道选择了哪个链接以及我该如何处理这些信息?
function fillYellow() {
var paintedDiv = document.getElementsByClassName('painted')[0];
paintedDiv.style.background = "yellow";
setTimeout(function () {
if (paintedDiv.style.background == "yellow") {
paintedDiv.style.background = "#e5e5e5";
}
}, 3000);
}
function fillYellow1() {
var paintedDiv = document.getElementsByClassName('painted')[1];
paintedDiv.style.background = "yellow";
setTimeout(function () {
if (paintedDiv.style.background == "yellow") {
paintedDiv.style.background = "#e5e5e5";
}
}, 3000);
}
function fillYellow2() {
var paintedDiv = document.getElementsByClassName('painted')[2];
paintedDiv.style.background = "yellow";
setTimeout(function () {
if (paintedDiv.style.background == "yellow") {
paintedDiv.style.background = "#e5e5e5";
}
}, 3000);
}
答案 0 :(得分:1)
我将使用带有data- *属性的jQuery事件处理程序,如
<ul>
<li><a href="#" class="fillYellow" data-target=".yellow">Using our site</a></li>
<li><a href="#" class="fillYellow" data-target=".yellow1">NonUsing our site</a></li>
<li><a href="#" class="fillYellow" data-target=".yellow2">Blablba our site</a></li>
</ul>
<h2 class="painted yellow">Using our site</h2>
<h2 class="painted yellow1">NonUsing our site</h2>
<h2 class="painted yellow2">BLAbla our site</h2>
然后
jQuery(function ($) {
$('.fillYellow').click(function () {
var $target = $($(this).data('target')).css('background', 'yellow');
setTimeout(function () {
$target.css('background', '#e5e5e5');
}, 3000);
})
})
演示:Fiddle
fillYellow
添加到所有触发元素data-target
属性,其中选择器值定位为必须突出显示的元素yellow
,yellow1
,...等
答案 1 :(得分:0)
为所有链接提供公共类。然后你可以使用像
$(".className").click(function(){ alert($(this).attr("href")); });
您不必为每个锚标记提供内联调用