javascript - Jquery How To Stop Append from Appending Previous Element -




i'm having trouble display star of each hotel , not sure on how it. have 5 hotels, , each has different value of hotelstar.

my javascript code:

function getstarhotel() {     var parent    = $(' p.star '),         imagepath = 'image/hotelstar.png',         img; (var = 0; < hotelstar; i++) {         img = new image();         img.src = imagepath;             $(parent).append('<img src="image/hotelstar.png" class="hotelstar" />')     }  } 

and html code is:

<h1>hotel 1</h1> <p class="star"><script>         hotelstar = 4;         getstarhotel();         </script></p> <h1>hotel 2</h1> <p class="star"><script>         hotelstar = 3;         getstarhotel();         </script></p> <h1>hotel 3</h1> <p class="star"><script>         hotelstar = 2;         getstarhotel();         </script></p> 

it adding previous hotel's stars. how can prevent adding same element?

instead of append() can use .html(), check updated code below

function getstarhotel() {     var parent    = $(' p.star '),         imagepath = 'image/hotelstar.png',         img,         star = '';     (var = 0; < hotelstar; i++) {             img = new image();             img.src = imagepath;                 star += '<img src="'+imagepath +'" class="hotelstar" />';         }     $(parent).html(star)  } 

i have simplified code. check updated snippet below

$('p.star').each(function(){      count = $(this).data('star'),      star = '',      imagepath = 'http://www.freeiconspng.com/uploads/download-png-image-star-png-image-1.png';      (var = 0; < count; i++) {          star += '<img src="'+imagepath +'" width="16" class="hotelstar" alt="'+i+'" />';      }      $(this).html(star)  })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>  <h1>hotel 1</h1>  <p class="star" data-star ="4" ></p>  <h1>hotel 2</h1>  <p class="star" data-star ="3"></p>  <h1>hotel 3</h1>  <p class="star" data-star ="2"></p>





wiki

Comments

Popular posts from this blog

Asterisk AGI Python Script to Dialplan does not work -

python - Read npy file directly from S3 StreamingBody -

kotlin - Out-projected type in generic interface prohibits the use of metod with generic parameter -