同步执行Jquery绑定

时间:2015-05-08 06:58:31

标签: javascript jquery

我目前正在$(window).load(function () { $("element").each( function() { /* . . . . */ var containerHeight = $(this).height(); var imgHeight = 0; //get the size of the full image. var imgLoad = $("<img />"); imgLoad.attr("src", imgSrc); imgLoad.bind("load", function () { imgHeight = this.height; }); heightDiff = (imgHeight - containerHeight); //some methods are called... //imgHeight is still set to 0 }); }); 声明中获得一些图片的大小。

我正在将一个函数绑定到它的load事件。虽然,我需要它在继续执行代码之前获取图像高度。

.trigger("custom-event")

我考虑使用.when()

然后检查是否使用Jquerys using (SqlConnection connection = new SqlConnection(connectionString)) using (SqlCommand command = connection.CreateCommand()) { command.CommandText = "Update TableName set C1 = @C1 where C2 = @C2 "; command.Parameters.AddWithValue("@C1", Textbox2.Text); command.Parameters.AddWithValue("@C2", Textbox1.text); connection.Open(); command.ExecuteNonQuery(); connection.Close(); } 方法

调用它

但这样做会有更简单(如果不是更好)的方法吗?

此致

3 个答案:

答案 0 :(得分:1)

一直如此经典的"how can I return values from an asynchronous function"问题。

你不能,期间。使用回调。

$("element").each(function () {
    var containerHeight = $(this).height(),
        imgSrc = "something";

    $("<img />", { src: imgSrc })
    .appendTo("#whatever")
    .on("load", function () { 
        var $img = $(this),
            heightDiff = ($img.height() - containerHeight);

        //some methods are called...
    });
});

答案 1 :(得分:0)

我认为你的做法几乎是正确的,当加载所有元素(包括图像)时会触发window.load。要获得每个图像的高度,请使用以下内容:

$(window).load(function(){

   // triggered when images are loaded

     $('img').each(function() {

          // get the height of each image
          var height = $(this).height();

      });
});

答案 2 :(得分:0)

您不能同步协商图像加载,因此您必须在加载事件回调函数中完成所有工作:

var imgLoad = new Image();
imgLoad.onload = function() {
    var imgHeight = this.height,
    heightDiff = (imgHeight - containerHeight);
    // do stuff here
};
imgLoad.src = imgSrc; // load image
相关问题