Javascript 单击图像时如何运行javascript函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8013041/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 04:23:05  来源:igfitidea点击:

how to run javascript function when click on image?

javascriptjquerytriggers

提问by Patrioticcow

i have this html:

我有这个 html:

<ul class="cont_ul4">

<li class="cont_li">
<div class="cont_picture">
<a href=""><img src="1.jpg" width="150" height="225" ></a>
</div>
</li>

<li class="cont_li">
<div class="cont_picture">
<a href=""><img src="2.jpg" width="150" height="225" ></a>
</div>
</li>

</ul>

and this function:

和这个功能:

function ajax_request() {
$('#placeholder').html('<p><img class="loader" src="/loader.gif"></p>');
$('#placeholder').load("/test.php?id=1234556");
}

what i need is when i click on the image to trigger this function.

我需要的是当我点击图像来触发这个功能。

with an input button i could do this:

使用输入按钮,我可以这样做:

<input type="button" onclick="ajax_request()" value="Click Me!" />

any ideas? Thanks

有任何想法吗?谢谢

回答by Vivin Paliath

Give your image an id:

给你的图片一个id:

<img id="myImage" src="1.jpg" width="150" height="225" style="cursor:pointer">

Then in Javascript:

然后在 Javascript 中:

$("#myImage").click(ajax_request);

Or if you want to run the same function for all images:

或者,如果您想对所有图像运行相同的函数:

$("img").click(ajax_request);

However it would be better to give your images a CSS class and then use that. That way you can restrict the click action to specific images:

但是,最好为您的图像提供一个 CSS 类,然后使用它。这样您就可以将单击操作限制为特定图像:

<img class="link-image" src="1.jpg" width="150" height="225">
...
<img class="link-image" src="2.jpg" width="150" height="225">

Then:

然后:

$(".link-image").click(ajax_request);

回答by James Johnson

Are you lookin for something like this?:

你在寻找这样的东西吗?:

$(function(){
    $("img").click(function(){
        ajax_request();
    });
});

回答by Naftali aka Neal

Try this:

尝试这个:

JS:

JS:

function ajax_request() {
   $('#placeholder').html('<p><img class="loader" src="/loader.gif"></p>');
   $('#placeholder').load("/test.php?id=1234556");
}


$('#run_ajax').click(ajax_request);

HTML:

HTML:

<input type="button" id='run_ajax' value="Click Me!" />