简体   繁体   中英

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

I have elements (images in <a> tags) list which arranged by dynamic ID. It is possible to select only one of those. Assume that I select any element. This time, I change its style and set "SelectedItem" value to its name attribute to find the selected item in future. I want that, when mouse over selected item, to change its src value, but jquery function does not work, because I set name="SelectedItem" attribute with javascript, in runtime, it works after reload a page. When I set name="SelectedItem" in the code (default, before runtime) it work. But I want to do it without reloading a page.

在此处输入图片说明

Shortly, when I do select operation I set name="SelectedItem" to selected image:

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

//my some operations

imgId_element.name = "SelectedItem";
}

And take name's value when UnSelect.

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

//my some operations

imgId_element.name = "";
}

I want to set unselect image to background of only selected images. When I Select/Unselect any item with SelectItem()/UnSelectItem() following mouseover()/mouseout() not work.

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

HTML is:

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

How can I solve this problem?

Try:

$('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";
});

By using the 3-argument variant of .on() , you set up a delegated handler on the <body> element. When the mouse events bubble up to that, the handler will check the target element against the selector.

Now, that said, using the "name" property/attribute for <img> elements doesn't make a lot of sense; that's not a valid attribute. You'd be better off adding/removing a class value:

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

and then:

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

etc. Finally, you'd be better off using the synthetic "mouseenter" and "mouseleave" events, as those get over some browser oddities.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM