我一直在寻找一种方法来确保当内容通过 jQuery 加载进出页面时相应地触发所有脚本。
到目前为止最好的方法是 live 函数,但我无法让它在加载时触发函数,只能对加载的元素进行操作。
EG。
$(document).ready(function(){
$('textarea').live('keyup',function(){
$(this).innerHeight(20 + (16 * ($(this).prop('scrollHeight') / $(this).css('line-height').replace('px', '') - 1.25)));
});
$('textarea').trigger('keyup');
});
这将使 textarea 在 keyup 函数上正确执行,但不会触发初始 $('textarea').keyup();
我该怎么做/有没有更好的方法来实现我所追求的目标。`
我已经做到了这一点,但页面加载后我的初始调用不起作用:
$(document).ready(function(){
$(document).on('keyup', 'textarea',function(){
$(this).innerHeight(20 + (16 * ($(this).prop('scrollHeight') / $(this).css('line-height').replace('px', '') - 1.25)));
});
$('textarea').trigger('keyup');
});
最佳答案
首先,您要使用 trigger()
来触发事件。
另外,不要使用 live()
,因为它已被弃用。而是使用 on()
。语法略有变化:
$(document).ready(function(){
$(document).on('keyup', 'textarea', function(){
$(this).innerHeight(20 + (16 * ($(this).prop('scrollHeight') / $(this).css('line-height').replace('px', '') - 1.25)));
});
$('textarea').trigger('keyup');
});
$(document).on('keyup', 'textarea', function)
中的选择器工作原理如下:
- 在
document
中查找与textarea
匹配的元素(这也适用于页面加载后添加的元素) - 如果
keyup
事件被触发,则执行回调方法
因此,您可以编写比文档
更具体的内容来减少计算时间。例如:
$('#myForm').on('keyup', 'textarea', function)
关于javascript - jQuery live() 函数用于网站大量使用 ajax,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12744423/