簡體   English   中英

更改元素的屬性值后,jQuery函數不起作用

[英]Jquery function does not work after change element's attribute value

我有按動態ID排列的元素( <a>標記中的圖像)列表。 只能選擇其中之一。 假設我選擇了任何元素。 這次,我更改其樣式,並將“ SelectedItem”值設置為其名稱屬性,以在將來查找所選項目。 我希望當鼠標懸停在選定項目上時更改其src值,但是jquery函數不起作用,因為我使用javascript設置了name =“ SelectedItem”屬性,因此在運行時,它在重新加載頁面后可以工作。 當我在代碼中設置name =“ SelectedItem”時(默認值,運行時之前),它將起作用。 但我想這樣做而無需重新加載頁面。

在此處輸入圖片說明

很快,當我選擇操作時,我將name =“ SelectedItem”設置為所選圖像:

function SelectItem(id) {
var imgId = 'productImage_' + id;
var imgId_element = document.getElementById(imgId.toString());

//my some operations

imgId_element.name = "SelectedItem";
}

並在取消選擇時取名稱的值。

function UnSelectItem(id) {
var imgId = 'productImage_' + id;
var imgId_element = document.getElementById(imgId.toString());

//my some operations

imgId_element.name = "";
}

我想將取消選擇圖像設置為僅所選圖像的背景。 當我使用SelectItem()/UnSelectItem() Select/Unselect任何項目時, mouseover()/mouseout()不起作用。

$("img[name='SelectedItem']").mouseover(function () {
            $(this).attr("src", "/Content/images/select.png");
        }).mouseout(function () {
            $(this).attr("src", "/Content/images/unselect.png");
});

HTML是:

<img src="@Url.Content("~/Content/images/select.png")" id='productImage_@(Model.Id)'  data-id='@Model.Id'  @{if (Model.IsSelected) { <text>name="SelectedItem"</text>} }  alt="" />

我怎么解決這個問題?

嘗試:

$('body').on('mouseover', 'img[name=SelectedItem]', function() {
  this.src = "/Content/images/select.png";
}).on('mouseout', 'img[name=SelectedItem]', function() {
  this.src = "/Content/images/unselect.png";
});

通過使用.on()的3參數變體,您可以在<body>元素上設置委托處理程序。 當鼠標事件冒泡時,處理程序將根據選擇器檢查目標元素。

話雖如此,對<img>元素使用“名稱”屬性/屬性沒有多大意義; 這不是有效的屬性。 您最好添加/刪除值:

function SelectItem(id) {
  $('#productImage' + id).addClass('SelectedItem');
}

接着:

$('body').on('mouseover', '.SelectedItem', function() { ... })

最后,最好使用合成的“ mouseenter”和“ mouseleave”事件,因為它們會克服一些瀏覽器異常。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM