gpt4 book ai didi

jquery - 如何使用 This 来改进和简化代码

转载 作者:行者123 更新时间:2023-12-01 07:58:17 24 4
gpt4 key购买 nike

我在一个页面上有几篇文章,并且有一个加号来展开文本。我所做的代码需要更加有效。此代码仅在我有一篇文章时才有效,因为当我单击加号时,所有文章都会受到影响。

我想我的代码可以通过使用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");
}
});

最佳答案

首先,您需要将点击事件绑定(bind)到所有文章都会有的内容。 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 - 如何使用 This 来改进和简化代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21972878/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com