我的jQuery函数存在问题。
此代码有效:
$("input.read_picture").on('keyup', function () {
$("#load_picture").attr('src', $(this).val());
$("#load_picture").error(function(){
$(this).attr('src', 'http://www.rnc-ci.net/images/joomlart/demo/default.jpg');
});
$("#show_picture").css('display', 'block');
});
但是当我想将我的函数存储到我的jQuery事件中时,它并不起作用。什么都没有显示。
以下代码不起作用:
function changePicture(url) {
$("#load_picture").attr('src', url);
$("#load_picture").error(function(){
$(this).attr('src', 'http://www.rnc-ci.net/images/joomlart/demo/default.jpg');
});
$("#show_picture").css('display', 'block');
}
$("input.read_picture").on('keyup', changePicture($(this).val()));
感谢您的帮助!
答案 0 :(得分:4)
此,
$("input.read_picture").on('keyup', changePicture($(this).val()));
加载处理程序后,将立即调用该函数。
使用回调
$("input.read_picture").on('keyup', function(){
changePicture($(this).val())
});
答案 1 :(得分:0)
jQuery
.on
处理程序期望函数作为第二个参数。您正在调用函数,而不是将其作为参数传递。调用函数不返回任何内容,因此undefined
作为handler
函数传递。
只需传递保存函数定义的函数名称,而不是调用函数。您可以在this.value
或$(this).val()
访问函数体中的值,因为this
指的是调用了哪个事件的DOM-Element
。
function changePicture() {
var url = this.value;
$("#load_picture").attr('src', url);
$("#load_picture").error(function() {
$(this).attr('src', 'http://www.rnc-ci.net/images/joomlart/demo/default.jpg');
});
$("#show_picture").css('display', 'block');
}
$("input.read_picture").on('keyup', changePicture);
或者对于您当前的实现,changePicure
必须返回一个要调用的函数作为keyup
的处理函数
function changePicture(url) {
return function() {
$("#load_picture").attr('src', url);
$("#load_picture").error(function() {
$(this).attr('src', 'http://www.rnc-ci.net/images/joomlart/demo/default.jpg');
});
$("#show_picture").css('display', 'block');
};
}
$("input.read_picture").on('keyup', changePicture('ANY_VALUE AS $(this).val() will not wors due to invalid context of this'));