开发者

First time variable is stored it is Undefined, every other time it works? Uses jQuery, JavaScript, Ajax

开发者 https://www.devze.com 2023-02-27 23:56 出处:网络
This is part of a function: var editid; $(\"div.editable\").click(function(e) { if ($currentInput == null)

This is part of a function:

var editid;   
$("div.editable").click(function(e) {   
    if ($currentInput == null)   
        return;    

    var css = GetCssProperties();    
    $(this).css(css);
    editid = $(this).attr("id");
    $currentInput = null;
    $("label").html("");
});

I think that the problem is here. If need be, I will post the entire thing.

Basically, the first time that var editid is stored, it is an undefined value.

The variable is send to a PHP page, and I had it echo the result back on the page.

Without fail, the first time that it stores its value onclick is "undefined" and every other time it stores the appropriate value.

Here is the entire thing:

<script>

$(document).ready(function(){
var $currentInput = null;

$("#border_button, #background_color_button, #opacity_button").click(function() {
    if ($currentInput == null) {
        $currentInput = $(this).prev();
        $("label").html($currentInput.attr("id"));
    }
});

var editid;
$("div.editable").click(function(e) {
    if ($currentInput == null)
        return;

    var css = GetCssProperties();    
    $(this).css(css);
    editid = $(this).attr("id");
    $currentInput = null;
    $("label").html("");
});

function GetCssProperties() {
    if ($currentInput == null) return null;

    var value = $currentInput.val();


    if ($currentInput.attr("id") == "background-color") {
        ajaxStyle(value, 1, editid)
        return {
        "background-color": value
        }
    }
    if ($currentInput开发者_如何学JAVA.attr("id") == "border-radius") {
        ajaxStyle(value, 2, editid)
        return {
        "border-radius": value
        }
    }
    if ($currentInput.attr("id") == "opacity") {
        ajaxStyle(value, 3, editid)
        return {
        "opacity": value
        }
    }
}

});


You call GetCssProperties() before you set the value of the variable. By this the first time the variable will be undefined if you try to access it inside GetCssProperties(), because you have globally declared it, but it still has no value.

Change the order to this:

 editid = $(this).attr("id");
 var css = GetCssProperties();    
0

精彩评论

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