我在页面上有几篇文章,并且有一个加号来扩展文本。我所做的代码需要更有效。只有当我有一篇文章时,此代码才有效,因为当我单击加号时,所有文章都会受到影响。
我猜我的代码可以通过使用this
进行改进,但是我不确定如何并且会提出一些指导和技巧以进行改进。
<article>
<header>
<img src="bilderGuide/bilderTips/oresundsbron.jpg" alt="Öresundsbron"/>
<div class="articleContent">
<div class="imageTextContainer">
<p class="image">Some text for the image</p>
</div>
<h2>Headline</h2>
<p>
Text that are always visible....
</p>
<p class="extraTips1">
Here is the hidden text
</p>
<!--<a id="tips1" href="#">Show the rest</a>-->
<div class="articleContentArrow"></div>
<div class="plus"><a href="#" id="tips1" ><img src="bilderGuide/bilderLayout/plus.png" /></a></div>
</div>
</header>
$("#tips1").click(function(e){
e.preventDefault();
$(".extraTips1").slideToggle("fast");
var src = $('.plus img').attr('src');
if(src == "bilderGuide/bilderLayout/plus.png") {
$(".plus img").attr("src","bilderGuide/bilderLayout/minus.png");
}
else {
$(".plus img").attr("src","bilderGuide/bilderLayout/plus.png");
}
});
最佳答案
首先,您需要将click事件绑定到所有文章都会拥有的东西。 ID是唯一的,因此#tip1
不可用。我认为您的<div class="plus">
将是一个不错的选择。
$('div.plus').click(function(e){
e.preventDefault(); // are you sure you need this?
var article = $(this).parents('article');
var extras = article.find('p.extraTips1').slideToggle('fast');
var img = article.find('.plus img');
if(img.attr('src') == "bilderGuide/bilderLayout/plus.png") {
img.attr('src','bilderGuide/bilderLayout/minus.png');
}
else {
img.attr('src','bilderGuide/bilderLayout/plus.png');
}
});
传递事件时,
this
引用HTML元素,而不是jQuery元素。我们首先要做的是获取基本容器元素并将其缓存。每当我们需要在文章中找到一个元素时,它都会搜索元素的更小子集-这样效率更高,还使您可以将同一事件用于多个文章。关于jquery - 如何使用它来改进和简化代码,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21972878/