[英]How to get ID of img and then use that to change contents of DIV
Ok, so I have a series of images that when clicked on will change the contents of a DIV with that image's ALT text. 好的,所以我有一系列图像,当单击这些图像时,将使用该图像的ALT文本更改DIV的内容。 Here is the code for that-
这是该代码-
$(function() {
$('#dalton').click(function() {
var alt = $(this).attr('alt');
$('.article_desc').html(alt);
});
$('#rutherford').click(function() {
var alt = $(this).attr('alt');
$('.article_desc').html(alt);
});
});
And I have this working just fine, but the issue is, if I have several images within the page, how can I optimize the code so I don't have to repeat it for each image? 而且我的工作效果还不错,但是问题是,如果页面中有多个图像,我该如何优化代码,而不必为每个图像重复它?
I thought about setting a variable to the image ID- 我考虑过为图片ID设置一个变量-
$(function() {
$('img').click(function() {
var imgid = this.id;
But I don't know how to marry the two together. 但是我不知道如何将两者结合在一起。
EDIT: Here is the HTML for that section: 编辑:这是该部分的HTML:
<section class="section1"> <article> <ul> <li><img src="plumpudding.gif" id="dalton" alt="Lorem ipsum dolor sit amet"></li> <li><img src="rutherford.png" id="rutherford" alt="Lorem ipsum dolor sit amet, consectetur adipisicing elit</li> <li><img src="bohr.gif" id="bohr" alt="Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi"></li> </ul> <div class="clearfix"></div> <div class="article_desc" id="article_desc">Click on the picture for description.</div> </article> </section>
Try this....So that you can get all clicked image alt
information.Note that all img
tags must have class='image'
and define the id for text area id= 'article_desc'
where you want to display alt
information. 尝试此操作。...以便您可以获得所有单击的图像
alt
信息。请注意,所有img
标签必须具有class='image'
并为要显示alt
信息的文本区域id= 'article_desc'
定义id。
$('.image').click(function() {
var alt = $(this).attr('alt');
$('#article_desc').append(alt);
});
Making a named function could be helpful here. 在此处创建命名函数可能会有所帮助。
$(function () {
$("#dalton").click(setDescriptionToAlt);
$('#rutherford').click(setDescriptionToAlt);
// OR use a class given to each element.
$(".image-with-alt").click(setDescriptionToAlt);
});
function setDescriptionToAlt() {
var alt = $(this).attr("alt");
$(".article_desc").html(alt);
}
By having a named function you just need to reference it instead of copying the inline anonymous function every time. 通过使用命名函数,您只需要引用它即可,而不必每次都复制内联匿名函数。 From there you can decide to do a click event for each element id you need or you could assign a class to each element to be affected and use that instead.
从那里,您可以决定对所需的每个元素ID进行一次click事件,或者可以为要受影响的每个元素分配一个类,并使用该类。
Instead of id's of elements use class name 使用类名代替元素的id
$('.image').click(function() {
var alt = $(this).attr('alt');
$('.article_desc').html(alt);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.