【问题标题】:jQuery Newbie, need a little helpjQuery新手,需要一点帮助
【发布时间】:2011-01-21 19:47:06
【问题描述】:

好的,所以我正在重新创建此功能:

http://www.w3.org/html/logo/#the-technology

我目前拥有它,因此当您单击链接时,它将向与该链接相关的图像添加一个类(<a> 上的 href="#one",然后在<img>),但是它目前没有遍历每个 <a> 标签,只有一个标签。而且它也没有删除我要求的课程。

代码如下:

JS

$(document).ready(function() {

var container = '#portfolio #text_container';

var img_container = '#portfolio #image_container';

$(container).children('a').bind('click', function() {

var this_attr = $(this).attr('href');

var this_img = $(img_container).find('img').attr('id');

if(this_attr == this_img) {

    //$(img_container).find('img').hasClass('current').removeClass('current');

        // ^^^ This line isn't working, any ideas? :/

    $(img_container + ' img[id*="' + this_attr + '"]').addClass('current');

}

else {

    alert(this_img + ' this img');

        alert(this_attr + ' this attr');

}

  });

});

而HTML如下

<div id="portfolio">

    <div id="image_container">
        <img src="http://static.jquery.com/files/rocker/images/logo_jquery_215x53.gif" alt="" class="current" id="#one" />
        <img src="http://static.jquery.com/files/rocker/images/btn_downloadLarge.gif" alt="" id="#two" />
    </div>

    <div id="text_container">
        <a href="#one" class="link">Item 1</a>
        <a href="#two" class="link">Item 2</a>

        <p id="#one" class="current">A bunch of text!</p>
        <p id="#two">The second bunch of text!</p>
    </div>

</div>

如果您需要更多信息,请告诉我:)

rcravens 用下面的代码解决了这个问题..

JS

$(document).ready(function() {


    $('#text_container a').click(function(evt) {
        evt.preventDefault();

        $('.current').removeClass('current');

        var href = $(this).attr('href');

        $("." + href).addClass('current');


    });

还有 HTML..

<div id="portfolio">

    <div id="image_container">
        <img src="http://static.jquery.com/files/rocker/images/logo_jquery_215x53.gif" alt="" class="one current" />
        <img src="http://static.jquery.com/files/rocker/images/btn_downloadLarge.gif" alt="" class="two" />
    </div>

    <div id="text_container">
        <a href="one" class="link">Item 1</a>
        <a href="two" class="link">Item 2</a>

        <p class="one current">A bunch of text!</p>
        <p class="two">The second bunch of text!</p>
    </div>

</div>

【问题讨论】:

标签: javascript jquery


【解决方案1】:

我对你正在尝试做的事情的解释是:

http://jsfiddle.net/rcravens/wMhEC/

代码稍作改动。您不应该有多个具有相同 id 的元素。

鲍勃

【讨论】:

  • 哇,就是这么简单:x 是的,这正是我想要的——谢谢! :)
  • 也请在此处发布您的解决方案。 Stack Overflow 的实用性不应依赖于其他站点的可用性。
【解决方案2】:

这不起作用的原因:

if(this_attr == this_img)

是因为this_attr 是一个 URL 而this_img 是一个 ID 属性值。

【讨论】:

    猜你喜欢
    • 2017-09-27
    • 1970-01-01
    • 1970-01-01
    • 2023-04-07
    • 2011-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-25
    相关资源
    最近更新 更多