这是我的代码 - 非常简单:
$(document).ready(function(){
$(".location").each(function(){
$(this).click(function(){
$("map").hide();
var class = $(this).attr("data");
$(".location").removeClass("activeLocation");
$(this).addClass("activeLocation");
$("." + class).show();
})
})
});
HTML
<div id="locations">
<div class="location activeLocation" data="brian">1205 S 75th St</div>
<div class="location one" data="mark">6603 A Royal Street</div>
<div class="location" data="dan">4725 Merle Hay Rd</div>
<div class="location" data="andy">62 Soccer Park Road</div>
<div id="mapviewer" class="brian map">Map to 1205 S 75th Street</div>
<div style="display: none;" id="mapviewer" class="mark map">Map to 6603 A Royal Street</div>
<div style="display: none;" id="mapviewer" class="dan map">Map to 4725 Merle Hay Rd</div>
<div style="display: none;" id="mapviewer" class="andy map">Map to 62 Soccer Park Road</div>
</div>
如果我注释掉两行,那么一切都有效:
var class = $(this).attr("data");
$("." + class).show();
如果没有这两行评论,根本就没有行动。这两行代码看起来不错。 我错过了什么?
答案 0 :(得分:1)
class
是reserved word (for future use) [MDN]。使用其他变量名称(例如cls
)。
此外,您应该使用HTML5 data-*
attributes。
答案 1 :(得分:0)
在行
之后var class = $(this).attr("data");
DO
console.log(class)
查看它包含的内容。此外,您不必将此全部包装在each()函数中,只需将第一行更改为
即可$('.location').click(function() {...
函数中的所有内容都是这个.location
对象
答案 2 :(得分:0)
您的JS代码修改如:
$(document).ready(function(){
$(".location").each(function(){
$(this).click(function(){
$(".map").hide(); // <--- here you wrote map").hide()
var cls = $(this).attr("data"); // <--- at Felix Kling advice
$(".location").removeClass("activeLocation");
$(this).addClass("activeLocation");
$("." + cls).show(); // <---- at Felix Kling adive
})
})
});
请避免使用您使用的语言(php,asp.net等)或OOP字段中的关键字保留关键字。
答案 3 :(得分:0)
$(".location").on('click', function(){
$(".map").hide();
$(".location").removeClass("activeLocation");
$(this).addClass("activeLocation");
$("." + $(this).attr("data")).show();
});