简体   繁体   English

未调用Onclick函数

[英]Onclick function not being called

I have the following code http://jsfiddle.net/6xcn6gzj/ , I need to remove an element off the page using its attribute, so I opted for jQuery's remove. 我有以下代码http://jsfiddle.net/6xcn6gzj/ ,我需要使用其属性从页面上删除一个元素,因此我选择了jQuery的删除。 My problem is that once I click on the image, nothing happens. 我的问题是,一旦我单击图像,什么都不会发生。 I tried calling the function from javascript itself and it was working perfectly. 我尝试从javascript本身调用该函数,并且运行良好。 For some reason, the event is just not happening. 由于某种原因,该事件只是没有发生。

HTML: HTML:

<div>
    <img src="whatever" alt="test" onclick="close('test')">
</div>

Javascript: Javascript:

console.log('hi');
function close(template) {
    console.log(template);
    $('body').find('img[alt="'+template+'"]').remove();
}

The console is logging "hi" which indicates that javascript is running fine but it never logs the template name. 控制台正在记录“ hi”,这表示javascript运行良好,但是从不记录模板名称。 Any help is appreciated. 任何帮助表示赞赏。

Two problems: 两个问题:

  • Don't name your function close , that will conflict with window.close 不要将函数命名为close ,这将与window.close冲突
  • Your fiddle was set to load your code in the onload handler, so your function was local to that function. 您的小提琴被设置为在onload处理程序中加载代码,因此您的函数是该函数的本地函数。 Change your fiddle to load the script in the <head> http://jsfiddle.net/6xcn6gzj/7/ 更改小提琴以将脚本加载到<head> http://jsfiddle.net/6xcn6gzj/7/

 function doClose(template) { console.log(template); $('body').find('img[alt="' + template + '"]').remove(); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div> <img src="whatever" alt="test" onclick="doClose('test')" /> </div> 

Maybe you should just call this.remove()? 也许您应该只调用this.remove()?

<div>
    <img src="whatever" alt="test" onclick="this.remove()">
</div>

http://jsfiddle.net/6xcn6gzj/2/ http://jsfiddle.net/6xcn6gzj/2/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM