使用 jQuery 从 HTML 获取 id,给出意想不到的结果

Getting id from HTML with jQuery giving unexpected results

本文关键字:意想不到 结果 id jQuery HTML 获取 使用      更新时间:2023-09-26
我想先

说一个事实,即我不能强调我对jQuery的陌生程度,所以这将是一个非常简单的问题。

我正在尝试熟悉jQuery,并且正在制作一个玩具应用程序,该应用程序只是替换了mouseovermouseleave上的一些HTML。

我有以下从w3schools借来的代码。

<!DOCTYPE html>
<html>
<head>
<style>
#header {
    background-color:black;
    color:white;
    text-align:center;
    padding:5px;
}
#nav {
    line-height:30px;
    background-color:#eeeeee;
    height:300px;
    width:100px;
    float:left;
    padding:5px;          
}
#section {
    width:350px;
    float:left;
    padding:10px;        
}
#footer {
    background-color:black;
    color:white;
    clear:both;
    text-align:center;
   padding:5px;      
}
</style>
<script src="jquery.min.js"></script>
</head>
<body>
<div id="header">
<h1>City Gallery</h1>
</div>
<div id="nav">
<a href="#" class='link' id="london-btn">London</a><br>
<a href="#" class='link' id="paris-btn">Paris</a><br>
<a href="#" class='link' id="tokyo-btn">Tokyo</a><br>
</div>
<div id="section">
<h2>London</h2>
<p>
London is the capital city of England. It is the most populous city in the United Kingdom,
with a metropolitan area of over 13 million inhabitants.
</p>
<p>
Standing on the River Thames, London has been a major settlement for two millennia,
its history going back to its founding by the Romans, who named it Londinium.
</p>
</div>
<div id="footer">
Copyright © W3Schools.com
</div>
<script>
$link = $(".link")
var original = $("#header").html();
$(".link").mouseover(function(){
 $("#header").html("<h1>I mousedover on "+ $link.attr("id") + "</h1>");
});

$(".link").mouseleave(function(){
 $("#header").html(original);
});

</script>
</body>
</html>

我正在使用jquery 2.1.3。我希望当我的鼠标悬停在london-btn上时看到"我鼠标悬停在伦敦-btn"上,当我的鼠标悬停在paris-btn上时,"我鼠标悬停在巴黎-btn"上,当我的鼠标悬停在tokyo-btn上时,"我鼠标悬停在东京-btn上",以及"城市画廊"。

几乎可以工作,但是当我将鼠标悬停在任何按钮上时,它总是说"我鼠标悬停伦敦-btn"。

这只是 DRY 开发和 jQuery 中的一个小练习。有什么建议吗?

谢谢埃里普

您需要

获取要悬停的元素的id,而不是在mouseover事件侦听器中检索第一个.link元素的id

在事件侦听器中,this 是指当前悬停在上面的元素,因此您可以使用 $(this).attr("id")this.id 访问id

这里的例子

$(".link").on('mouseover', function () {
    $("#header").html("<h1>I mousedover on " + this.id + "</h1>");
});

值得指出的是,$(".link")返回元素的集合(jQuery对象(。使用 $(".link").attr("id") 访问id时,您正在访问 jQuery 对象中第一个元素的id。这就是为什么你的短信总是说"伦敦"。