0

我有这个:

$('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>

是我的语法或用法在这里错误吗?

4

1 回答 1

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>

于 2012-06-10T22:06:56.533 回答