Home > Software engineering >  JQuery Change the image of a specific numeric ID
JQuery Change the image of a specific numeric ID

Time:08-12

I'm using a translator, so I hope you understand even if the grammar is wrong. Also, there are many things that are lacking because it hasn't been long since I learned J-Query. I want to change the SRC of an image with an ID of eListPrdImage***_1_* "*" is number The number attached to the ID is given sequentially by the server, and I want to change the image when the ID is a specific number.

$(function () {
    $("[id*=eListPrdImage]").on('ready', function () {
        var num1 = this.id.slice(13);
        var num2 = this.id.slice(19);
            if (num1 == '123' && num2 == '1') { 
            $(this).attr("src", "img.jpeg");
            }
    });
});

I wrote the code like this, but it doesn't work at all. Can you give me advice on how to modify the code?

CodePudding user response:

Retrieving id this way may not work.

Change that as below.

var num1 = $(this).attr('id').slice(13);

Edit: Try the below, by adding the code inside document.ready function.

$(document).ready(function(){
  $("[id*='img']").each(function () {
        var num1 = this.id.slice(13);
        var num2 = this.id.slice(19);
        if (num1 == '123' && num2 == '1') { 
            $(this).attr("src", "img.jpeg");
        }
  });
});
  • Related