简单的jQuery变量事件 [英] simple jQuery variable event

查看:69
本文介绍了简单的jQuery变量事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这是一个基本问题,但这是让我明白的问题.

I know this is a basic question, but these are the ones that get me.

我定义一个变量:

var img_w = $('#image').width();

然后我这样做:

$(document).ready(function() {
    if (img_w > 100) {
        //do stuff
    }
});

我的图像是从单独的html加载的,并使用jQuery设置样式,然后符合> 100的标准,但是为时已晚.所以我尝试:

My image is loaded from a separate html, styled with jQuery, and then fits the >100 criteria, but it's too late. So I try:

$(window).load(function()
$(window).on('load' function()
$(window).onload(function()
$(window).ready(function()

依此类推...但是由于事件的顺序无济于事.

And so on an so forth... But to no avail, because of the order of events.

因此,简单的解决方案是在img_w大于100时创建一个事件.但是由于某些原因,我不知道执行此操作的最佳方法.我敢肯定我缺少一个简单的解决方案.任何帮助都感激不尽. :)

So the simple solution is to make an event for when img_w is greater than 100. But for some reason I can't figure out the best way to do this. I'm sure there's a simple solution I'm missing. Any help will be much appreciated. :)

edit:为您扩展有关正在发生的问题的信息; div的宽度应设置为img_w.从外部html文件加载img_w从中获取值的图像.用于设置div宽度以及变量位置的jQuery位于外部html文件中.

edit: To expand on you questions about what's going on; A div is to have it's width set to img_w. The image that img_w get's it's value from is loaded from an external html file. The jQuery to set the div width, and where the variable is made, is in the external html file.

推荐答案

您可以利用DOMSubtreeModified事件,只要元素的属性发生更改,该事件就会被执行.

You can make use of DOMSubtreeModified event which gets executed anytime there is a change in the property of the element.

$('#image').bind("DOMSubtreeModified", CheckHeight);

这里是一个示例: https://jsfiddle.net/DinoMyte/6d5ry9br/

更新:由于DOMSubtreeModified已过时,并且可能不再与所有浏览器兼容,另一个可能的选择是将事件处理程序委派给该元素,并在外部事件调用期间手动调用change事件. :

UPDATE : Since DOMSubtreeModified is depreciated and may no longer be compatible with all browsers, the other possible option is to delegate an event handler to the element and manually invoke the change event during an external event invokation:

$('#image').bind("DOMModified", CheckHeight);
$("#image").triggerHandler('DOMModified');

这里是一个示例: https://jsfiddle.net/DinoMyte/6d5ry9br/1/

这篇关于简单的jQuery变量事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆