javascript - jquery调用函数

标签 javascript jquery function callback

我需要在这段代码之后执行posImgCar()函数

$('details_img').click(function(i){
    ...
   $(this).closest(".page").find(".car_detail").parent().attr('href', $(this).attr('src'));
   ...
});

所以我有这个:

 $('details_img').click(function(i){
    ...
   $(this).closest(".page").find(".car_detail").parent().attr('href', $(this).attr('src'));
  /*--->*/ posImgCar();
   ...
});

posImgCar();

但当我在同一张图像中单击两次时,它只会调用 posImgCar()

我应该如何完成它?

最佳答案

在您的代码示例中,您将单击事件处理程序绑定(bind)到 $('details_img') ,这意味着您将其绑定(bind)到自定义元素,例如,就好像您的 HTML 包含 <details_img></details_img> 。我假设details_img实际上是一个类名或id。

在您的代码示例中,您还调用 postImgCar()将点击事件处理程序附加到details_img之后,大概是在页面加载时。如果这不是您想要做的,那么当然就删除那个额外的调用。

如果你想要postImgCar()每次用户单击details_img时执行,并且在设置href属性后,如果details_img是类名,则执行此操作:

$('.details_img').click(function(i){
    // ...
    $(this).closest(".page").find(".car_detail").parent().attr('href', $(this).attr('src'));
    posImgCar();
    // ...
});

或者这样,如果details_img是一个id:

$('#details_img').click(function(i){
    // ...
    $(this).closest(".page").find(".car_detail").parent().attr('href', $(this).attr('src'));
    posImgCar();
    // ...
});

最后,如果您使用的是 jQuery 1.6 或更高版本,请考虑使用 .prop()方法,而不是 .attr() 。请参阅jQuery API documentation for .prop()以获得解释。

关于javascript - jquery调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8760103/

相关文章:

Jquery/CSS "Fan Out"动画

javascript - 原型(prototype)与函数定义

azure - HTTP 401 Azure Terraform 操作组向 Azure 函数发送日志搜索警报

javascript - Bootstrap - 为每个环境调整按钮和文本字段的动态高度

Javascript获取两个符号之间的字符串

javascript - 将 iFrame 内的 Fancybox 扩展到外部

c++ - 将 Void 作为指针传递给类,然后执行其内容

javascript - 避免对象突变

javascript - 为什么在此幻灯片上使用 setTimeout?

javascript - 如何避免数据结果中出现html代码