我有这个:
$('li').click(function() {
var currentSrc = $('img', this).attr('src').toString();
var grabAlt = $('img', this).attr('alt').split('|');
//alert(grabAlt[0]);
$('.imgSample img').attr('src', currentSrc);
$('.projectDescription').html('<p class="projectDescription">' + grabAlt[0].join('</p>'));
$('.projectTitle').html(grabAlt[1]);
});
当我删除[0]和[1]时,我可以发出警报,我正在考虑的是第一个值[0],确实替换项目描述,但是尝试将每个放在相应的位置不会工作。
相关html片段:
<section class="workArea">
<div class="imgSample"><img src="images/samples/testImage2.png" alt="This first part will be a short description. | this second part will be the title."></div>
<p class="projectDescription">This is to be replaced when an image is clicked on.</p>
<h3 class="projectTitle">To be replaced</h3>
</section>
</div>
<nav>
<ul class="print">
<li class="liRounded"><img width="50" height="50" src="images/samples/image1.png" alt="Should replace the content in the paragraph. | Replace title copy."></li>
<li class="liRounded"><img width="50" height="50" src="images/samples/image2.png" alt="Second. | Replace title 2."></li>
<li class="liRounded"><img width="50" height="50" src="images/samples/image3.png" alt="third. | Replace title 3."></li>
</ul>
</nav>
这是我的语法或用法吗?
答案 0 :(得分:0)
你几乎就在那里,但并不完全:
$('li').click(function() {
var img = $('img', this).get(0);
var src = img.src; // no need for .attr
var alt = img.alt; // ditto
var grabAlt = alt.split('|');
$('.imgSample img').attr('src', currentSrc);
$('.projectDescription').text(grabAlt[0]);
$('.projectTitle').text(grabAlt[1]);
});
大多数情况下,您无需在<p>
元素中添加新的.projectDescription
,只需更改其文本内容即可。
正如@gdoron提到的,.join()
没有做你认为它做的事情 - 它需要一个数组的字符串,并将它们与给定的一起连接起来分隔器。它没有将grabAlt[0]
与</p>
连接起来。