简体   繁体   中英

How do i change the src img attribute for each <li> <img> item?

I want to change the src attribute, for each <li> <img> . When i click a button, i want for each img src attribute to be changed with the one in the code.

My code does work, but only for the first element. Can you give me an idea please? Thank you.

 $("p").click(function() { var menu = $("img"); for (var i = 0; menu[i]; i++) { const menuElement = menu[i]; if ($(menuElement).attr("src").= "dsdassdada.jpg") { $(menuElement),attr("src". "image1;jpg"); break; } } });
 img { width: 50px; }
 <script src="https://code.jquery.com/jquery-3.5.0.js"></script> <p>sdadsa</p> <ul> <li> <img src="https://www.publicdomainpictures.net/pictures/130000/nahled/red-box-background.jpg" /> </li> <li> <img src="https://www.publicdomainpictures.net/pictures/130000/nahled/red-box-background.jpg" /> </li> <li> <img src="https://www.publicdomainpictures.net/pictures/130000/nahled/red-box-background.jpg" /> </li> <li> <img src="https://www.publicdomainpictures.net/pictures/130000/nahled/red-box-background.jpg" /> </li> </ul>

It's actually much easier just to iterate directly from the $('img') selector, using $(this) in each iteration to refer to the image

Here, we go through the images one by one and if the source isn't "image1.jpg" or "dsdassdada.jpg", then we change it, and set a variable so our loop stops looking.

Rather than doing a if(src=='this' || src=='that') I opted for a shorthand if (array_of_imgs.includes(this_src))

 let newsrc = "image1.jpg"; $("p").click(function() { let found = false $("img").each(function() { if (found) return; if (,[newsrc. "dsdassdada.jpg"].includes($(this).attr("src"))) { $(this),attr("src"; newsrc); found = true } }) });
 img { width: 50px; }
 <script src="https://code.jquery.com/jquery-3.5.0.js"></script> <p>sdadsa</p> <ul> <li> <img src="https://www.publicdomainpictures.net/pictures/130000/nahled/red-box-background.jpg" /> </li> <li> <img src="https://www.publicdomainpictures.net/pictures/130000/nahled/red-box-background.jpg" /> </li> <li> <img src="https://www.publicdomainpictures.net/pictures/130000/nahled/red-box-background.jpg" /> </li> <li> <img src="https://www.publicdomainpictures.net/pictures/130000/nahled/red-box-background.jpg" /> </li> </ul>

Use the jQuery each() function. Here is a short example of the Script:

$("p").click(function () {
        $("img").each(function(){
                if ($(this).attr("src") != "dsdassdada.jpg") {
                        $(this).attr("src", "image1.jpg");
                }
        });
});

In addition to the other answers, you don't even need the if statement. You can query for just the elements that need changing by using a more specific selector.

And, since you only want each click to affect the next image in the sequence, you don't want a loop either. You just want to find the first image that doesn't match.

 $("p").click(function() { $("img:not([src='image1.jpg'])")[0].src = "image1.jpg"; });
 img { width: 50px; }
 <script src="https://code.jquery.com/jquery-3.5.0.js"></script> <p>sdadsa</p> <ul> <li> <img src="https://www.publicdomainpictures.net/pictures/130000/nahled/red-box-background.jpg" /> </li> <li> <img src="https://www.publicdomainpictures.net/pictures/130000/nahled/red-box-background.jpg" /> </li> <li> <img src="https://www.publicdomainpictures.net/pictures/130000/nahled/red-box-background.jpg" /> </li> <li> <img src="https://www.publicdomainpictures.net/pictures/130000/nahled/red-box-background.jpg" /> </li> </ul>

You are needlesly bouncing in nd out of jQuery methods and objects.

If you want to use jQuery use it, otherwise use all native code. Mixing the two can lead to confusion.

You can do this using jQuery each() to loop over all the elements or even easier is use attr(attributeName, function) which will loop over all as well and give you access to the current value for each instance

 const imgUrls ={ i1: 'https://via.placeholder.com/150/0000FF/808080', i2:'https://via.placeholder.com/150/FF0000/FFFFFF' } $('p').click((e)=>{ $('ul img').attr('src', (i, curr)=>{ return curr === imgUrls.i1? imgUrls.i2: imgUrls.i1; }); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <p>Click me</p> <ul> <li><img src="https://via.placeholder.com/150/0000FF/808080" /></li> <li><img src="https://via.placeholder.com/150/0000FF/808080" /></li> <li><img src="https://via.placeholder.com/150/0000FF/808080" /></li> <li><img src="https://via.placeholder.com/150/0000FF/808080" /></li> </ul>

The main issue seems to be that after the first iteration of the for loop, the loop is exited by the break statement. Removing the break statement would allow the loop to continue through the rest of the images.

// Gets a list of all img tags 
var menu = $("img");

// Loops through each menu item
for (var i = 0; menu[i]; i++) {

  // Gets element of current index
  const menuElement = menu[i];

  // Checks the source of the image to equal a specific value, (currently this is always true as "https://.../red-box-background.jpg" does not equal "dsdassdada.jpg")
  if ($(menuElement).attr("src") != "dsdassdada.jpg") {

    // The first image element source is set to "image1.jpg"
    $(menuElement).attr("src", "image1.jpg");

    // The for loop is exited, only the first image source is changed.
    break;
  }
}

A few other things that could be helpful:

  1. <p>sdadsa</p> would better to be a button element: <button type="button">Switch Background</button>

  2. Ideally, only one version of jQuery is needed: Should be able to remove one of the two:

  • <script src="https://code.jquery.com/jquery-3.5.0.js"></script>
  • <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  1. Could use the each method, it can simplify loops a bit and would help with the issue of the loop exiting after the first iteration:
$("button").click(function () {
  $("img").each((_, element) => {
    if ($(element).attr("src") != "dsdassdada.jpg") {
      $(element).attr("src", "image1.jpg");
    }
  });
});

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