从另一个文件加载js函数

时间:2012-04-16 12:30:16

标签: javascript jquery

我有像这样的javascript

$.fn.hasBorder = function() {   
  if ((this.outerWidth() - this.innerWidth() > 0) ||  (this.outerHeight() - this.innerHeight() > 0)){
        return true;
    }
    else{
        return false;
    }
};

function removeImage(){
$(document).ready(function() {
  var selectedImgsArr = [];
   $("img").click(function() {

      if($(this).hasBorder()) {
          $(this).css("border", "");
          //you can remove the id from array if you need to
      }
      else {
         $(this).css("border", "1 px solid red");
         selectedImgsArr.push($(this).attr("id")); //something like this 
         alert(selectedImgsArr);
 }
   });

我将此脚本加载到我的页面。为了使用这个脚本

我写了这个

div load="removeImage">

什么不起作用?

2 个答案:

答案 0 :(得分:1)

您正在考虑“onload”事件。但这只能用于“身体”元素。即使这样有效,你也必须像这样写“... =”removeImage()“。

这里有关于SO的类似问题,this one解释了如何在“div”上加上“onload”。

答案 1 :(得分:1)

如果您在load上使用div,则无法在脚本上使用document.ready。因为如果你这样做,你所说的是:“在div load事件寄存器上,一个将在页面准备就绪时执行的监听器”。但是......在注册听众之前,该事件被解雇了。

此外,您无法在onload div上使用body

简而言之,就这样做:

$(document).ready(function() {
  var selectedImgsArr = [];
   $("img").click(function() {
      if($(this).hasBorder()) {
          $(this).css("border", "");
          //you can remove the id from array if you need to
      } else {
         $(this).css("border", "1 px solid red");
         selectedImgsArr.push($(this).attr("id")); //something like this 
         alert(selectedImgsArr);
      }
  });
});

然后从HTML中删除load="removeImage"

相关问题