简体   繁体   中英

jQuery: How to get value inside elements using index or jquery object

This is much like slider presentation:

<ul id='slider'>
   <li class="slide1">...</li>
   <li class="slide2">...</li>
   <li class="slide3">...</li>
   <li class="slide4 currentSlider">
      <div class="itemImage">../*image to display*/..</div>
      <span class="itemName">Bag</span>
      <span class="price">500</span>
   </li>
</ul>

I dynamically append currentSlider class in each li element whichever is on higher z-index (to diplay on top)

List of variables I already have:

  1. sliderIndex = li container index number
  2. sliderData = current slide jQuery object (li element)

My Goal is to get the price value ( 500 ) inside li currentSlider class so I can format it to currency.

My currency formatting code:

jQuery(function ($){
  mySlider.bind("slider.slide.onchange",function ( sliderIndex, sliderData ) {

 var price = $("span.price").html();

    $(".sliderPrice").text('$' + parseFloat(price , 10).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,").toString());

  });
});

I already have a final bunch of codes to make this things happened but unfortunately sometimes it shows/display the right currency format and sometimes shows $NaN . I mean NOT consistent.

You are getting the price value from price element without using the current slider li , please use the current slide object to get the price value: $("span.price",sliderData).html();

jQuery(function ($){
  mySlider.bind("slider.slide.onchange",function ( sliderIndex, sliderData ) {
    var price = $("span.price",sliderData).html();
    $(".sliderPrice").text('$' + parseFloat(price , 10).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,").toString());
  });
});
var price =  $(".currentSlider .price").text().replace(/[^0-9.]/g, "");
$(".sliderPrice").text('$' + parseFloat(price , 10).toFixed(2));

http://jsfiddle.net/e6F7G/1/

You'd probably be better off filtering the numbers when you fill the elements with prices, but this works nonetheless...

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