为什么jquery函数不能对具有相同ID的两个图像执行



我在asp.net MVC应用程序中有以下脚本来弹出图像

   $(document).ready(function () {
        $("#to-get-bigger").mouseover(function () {
            $(this).effect("bounce", { time: 3, distance: 40 });
        });
    });

在视图上,我有以下两张Id相同的图像:-

<a href="@Url.Action("StartAssessment", "StartAssessment", new { assessmentid = Model.AssessmentID })" 
onclick = "return confirm('This will make the Assessment avilable for the regestred user.')" > 
   <img id = "to-get-bigger" border="0" src="@Url.Content("~/content/images/assessment-button1.jpg")" alt="start assessment" />
</a>
 <a href="@Url.Action("StartAssessment", "StartAssessment", new { assessmentid = Model.AssessmentID })" 
onclick = "return confirm('This will make the Assessment avilable for the regestred user.')" > 
   <img id = "to-get-bigger" border="0" src="@Url.Content("~/content/images/assessment-button1.jpg")" alt="start assessment" />
</a>

但问题是Jquery函数只会执行和反弹一个图像,而不会对第二个图像起作用,尽管我已经读到Jquery选择器在这种情况下#to-get-bigger会返回所有具有此ID的元素,并且一旦用户在任何预期元素上移动鼠标,Jquery函数就会执行?BR

拥有多个具有相同id的元素是无效的,会导致这样的问题。id属性应该是唯一的。要引用具有单个属性的多个元素,请使用class:

HTML

<a href="@Url.Action("StartAssessment", "StartAssessment", new { assessmentid = Model.AssessmentID })" onclick="return confirm('This will make the Assessment avilable for the regestred user.')" > 
    <img class="to-get-bigger" border="0" src="@Url.Content("~/content/images/assessment-button1.jpg")" alt="start assessment" />
</a>
<a href="@Url.Action("StartAssessment", "StartAssessment", new { assessmentid = Model.AssessmentID })" onclick="return confirm('This will make the Assessment avilable for the regestred user.')">
    <img class="to-get-bigger" border="0" src="@Url.Content("~/content/images/assessment-button1.jpg")" alt="start assessment" />
</a>

jQuery

$(document).ready(function () {
    $(".to-get-bigger").mouseover(function () {
        $(this).effect("bounce", { time: 3, distance: 40 });
    });
});

Id必须是唯一的。jQuery使用的本地javascript方法document.getElementById()只返回它找到的具有特定ID的第一个元素。

如果您使用jQuery by ID选择元素,它将只返回一个元素,因为该ID只能有一个有效的元素。尽管我看到它在一些边缘情况下有效,例如使用jQuery corners插件,但即使在不使用唯一ID的情况下,这也不适用于所有浏览器。

不,它会得到一个名为#的Id的集合,并且Id在页面上必须是uniqe,因此应该使用css类。http://www.w3.org/TR/html4/struct/global.html#h-7.5.2为您提供了w3c关于其工作方式的规范。

最新更新