开发者

Can I get at attributes of individual elements that JQuery selects during selection?

I am using JQuery and the JQuery UI Slider to render some controls in my HTML page and I want to set the range of the slider from an attribute in my HTML.

Here is the code I use to initialize the sliders...

$( ".slider" ).slider(
  {
    range: "min",
    value: 0,
    min: 0,
    max: 5,
    slide: handleSlide
  }
);

Of course the max value is hard coded. What I would like to do in my code is...

<div class="slider" id="sliderA" max="10"></div>

but I can't figure out how to get at a开发者_如何学运维n attribute during selection.

I thought I may have access to it via this, like you do in JQuery's .each() but firebug tells me it is the document, so that doesn't work.

I want to do something like...

$( ".slider" ).slider(
  {
    range: "min",
    value: 0,
    min: 0,
    max: blah.getAttribute("max"),
    slide: handleSlide
  }
);

but I can't figure out what blah might be.

Is there an accepted way to do this? I confess that JQuery still has a bit of black magic for me but I am working under the presumption that the selector resolves to an array of objects somehow, so it feels like I should be able to get at the elements.


    $( ".slider" ).each(function()
    {
     $(this).slider(
      {
        range: "min",
        value: 0,
        min: 0,
        max: $(this).attr("max"),
        slide: handleSlide
      }
    );
    });


No, you can't.

Your code creates a single object literal, then passes it to a slider method. Inside the object literal, your outer $ call does not exist.

Instead, you need to call .slider() inside of .each, allowing you to create a separate object literal for each element.
Also, since you'd be creating the object literal in the each callback, it would have this from the each callback.


It looks like your best option is to get the value of your "max" attribute on the fly:

    $('.slider').each(function (index) {
        $(this).slider({
            max: $(this).attr('max'),
            slide: function (event, ui) {
                console.info(ui.value);
            }
        });
    });
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜