質問

I have an issue in JQuery in getting CLASS NAME of clicked element.

Here's my code so far: CODEPEN

HTML

<div class="sideNav">
    <a href="#" id="technical" class="servicesTech">
        <div class="sideThumb cap-left">
            <img src="http://lorempixel.com/200/200/technics" />
            <figcaption class="thumb_caption">Sample1</figcaption>
        </div>
    </a>
    <a href="#" id="sales" class="servicesSales">
        <div class="sideThumb cap-left">
            <img src="http://lorempixel.com/200/200/business" />
            <figcaption class="thumb_caption">Sample2</figcaption>
        </div>
    </a>
</div>

JQUERY

$(document).ready(function(){           

    $('a').bind('click', function(){
        idName = "#" + $(this).attr('id');
        className= $(this).attr('id');
        var getClassElem = $(this).attr('class');

        alert(getClassElem);

        $("a").removeClass();
        $(idName).addClass(className);
    });

});

Issue

It only works on first load of the page. but when I clicked the other MENU it doesn't show on ALERT. I just used ALERT for showing if it is retrieving correctlt.

Any help will so much appreciated. Thanks!

役に立ちましたか?

解決

You have written:

$('a').bind('click', function(){
    idName = "#" + $(this).attr('id');
    className= $(this).attr('id');
    var getClassElem = $(this).attr('class');

    alert(getClassElem);

    $("a").removeClass();
    $(idName).addClass(className);
});

It can be optimized as:

$('a').click(function(){
    $("a").removeAttr("class");
    $(this).addClass($(this).attr("id"));
});

Few other things:

  1. What are you trying to do?
  2. How can you have a <div> element inside an <a> element?
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top