开发者

Getting a variable value into a jQuery UI call

I'm using the HTML/CSS/JavaScript/jQuery to create a UI palette for a Sketchup plug-in. There are numerous instances within the palette which require an input box with an associated slider, so I've decided to make a "class" using JavaScript so I can stamp them out. The HTML for one of the input box/slider combos looks like this:

<span>H:&nbsp;<input type="text" class="InputBox" id="reg_panel_spacing_h"></span>
<div class="SliderSpan" id="reg_panel_spacing_h_slider"></div><br/>

The relevant portion of the JavaScript looks like this:

$(document).ready(function() {

    function InputBoxJS (id, mi, ma, numtype, slider) {

        this.current_val = mi;
        this.element_id = id;
        this.minimum = mi;
        this.maximum = ma;

        var self = this;

        // string for selecting element using jquery
        jq_id = "#" + this.element_id;

        // slider code (if input box has associated slider)
        if(slider = true) {
            slider_jq_id = jq_id + "_slider" // id for selecting slider; assumes it's input id + "_slider"          

            $(slider_jq_id).slider({
                min: mi,
                max: ma,
                value: self.current_val,
                slide: function(event,ui) {
                    $(jq_id).val(ui.value); // PROBLEMATIC LINE
                    call_ruby("manipulate_data", self.element_id);
                }
            });
        } // if slider = true   
    }

    // create script objects for two input boxes
    var reg_panel_spacing_h = new InputBoxJS("reg_panel_spacing_h", 500, 50000, 0, true);
    var reg_panel_spacing_v = new InputBoxJS("reg_panel_spacing_v", 500, 50000, 0, true);

});

The problem I'm having is that when I create two input boxes using this class (as shown in the above code), both sliders end up associated with the second input box. Specifically, the jq_id variable flagged in the above code as problematic ends up being set to "reg_panel_spacing_v" for both input boxes. What's bizarre is that jq_id is used a few lines above the "problematic line" to set slider_jq_id, and performs as expected when used there.

Basically what seems to be happening is that the function which contains the "problematic line" is getting associated with the slide event of ALL of the sliders when it's created, and it only uses the jq_id of the most recently-created input box. If change the "problematic line" like so:

$(("#" + self.element_id)).val(开发者_如何学Cui.value);

the problem is fixed. So, I have a workaround. I'm just hoping that someone would be able to explain to me exactly what's going on.

Many thanks!

Josh


Try making the variable local, like this:

var jq_id = "#" + this.element_id;

I suspect that without making it local it get global scope that explain the "bizarre" behaviour.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜