简体   繁体   English

外部.js文件上的“ onClick”

[英]“onClick” on external .js file

I'm new to Javascript and I'm triyng to perform an onClick event on an image in a external .js file using the html tag 我是Java语言的新手,我正尝试使用html标记在外部.js文件中的图像上执行onClick事件

<script type="text/javascript" src="embed.js">

The code inside "embed.js" is the following 以下是“ embed.js”中的代码

var image1=new Image();
image1.src="img.gif"
document.write('<IMG src='+image1.src+'>');


$(document).ready( function()
{
 $(image1).click( function()
{
    alert("Hello World");
    });
});   

As you can see, I'd like to show an alert when somebody click on the image, but the code I've posted doesn't work. 如您所见,当有人单击图像时,我想显示一个警报,但是我发布的代码不起作用。 Could you help me? 你可以帮帮我吗? Thanks! 谢谢! :) :)

@JD it the html code is @JD它的html代码是

<html>
<head>
    <title></title>

</head>

<body>
<script src="embed.js"></script>
</body>


</html>

The image that you attach the onclick to and the image that you put on the page are not the same. 您将onclick到的图像和放在页面上的图像是不同的。

Explanation: The string that you pass to document.write is parsed by the browser to create a new image element (albeit one that has the same src ) while image1 is a different image instance that is only in memory (not on the page), but it has the event listener. 说明:传递给document.write的字符串由浏览器解析,以创建一个新的图像元素(尽管具有相同的src ),而image1是仅在内存中(不在页面上)的另一个图像实例,但它具有事件侦听器。

To fix, replace 要修复,请更换

document.write('<IMG src='+image1.src+'>');

with

document.body.appendChild(image1);

Now you're dealing with only one image, which gets put on the page and the event listener. 现在,您只处理一张图像,该图像将被放置在页面事件侦听器上。

All the answers are correct 所有答案都是正确的

but you can insert the "image1" object directly in the DOM. 但是您可以直接在DOM中插入“ image1”对象。

Something like this: 像这样:

$(document).ready( function(){
    // Take care with the scope of image1

    var image1 = $("<img/>").attr("src","img.gif").appendTo("parentElementInDOMselector");

    image1.click( function(){
        alert("Hello World");
    });

});  

You can use appendTo, preppendTo, or functions like html(); 您可以使用appendTo,preppendTo或类似html()的函数; replace(); 更换(); etc... 等等...

Your selections are off, try: 您的选择已关闭,请尝试:

$("document").ready( function()
{
 $("#image1").click( function()
{
    alert("Hello World");
    });
});   

and add an id to the image tag 并将id添加到图片标签

<img id='image1' ...

JS fiddle http://jsfiddle.net/YS95J/ JS小提琴http://jsfiddle.net/YS95J/

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

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