Targeting Multiple Elements with One Function

时间:2016-07-11 20:02:58

标签: javascript jquery html css

I have a function that assigns dynamic classes to my div's. This function is a that runs on the page. After the page loads, all 10 of my primary 's have classes ".info1" or ".info2" etc...

I am trying to write a Jquery function that changes the class of the div you click on, and only that one. Here is what I have attempted:

$(".info" + (i ++)).click(function(){
    $(".redditPost").toggleClass("show")
});

I have also tried:

$(".info" + (1 + 1)).click(function(){
    $(".redditPost").toggleClass("show")
});

And

$(".info" + (i + 1)).click(function(){
    $(".redditPost").toggleClass("show")
});

EDITED MY HTML: DIV RedditPost is actually a sibling to Info's parent

<div class="listrow news">
    <div class="newscontainer read">
        <div class=".info1"></div>
        <div class="redditThumbnail"></div>
        <div class="articleheader read">
    </div>
    <div class="redditPost mediumtext"></div>
</div>

My issue is two fold.

  1. The variable selection for ".info" 1 - 10 isn't working because i doesn't have a value.
  2. If I did target the correct element it would change all ".redditPost" classes instead of just targeting the nearest div.

3 个答案:

答案 0 :(得分:1)

Try like this.

$("[class^='info']").click(funtion(){
    $(this).parent().find('.redditPost').toggleClass("show");
});

Alternative:

$('.listrow').each(function(){
    var trigger = $(this).find("[class^='info']");
    var target = $(this).find('.redditPost');

    trigger.click(function(){
        target.toggleClass("show");
    });
});

答案 1 :(得分:1)

Try this

$("div[class*='info']").click(function(){
    $(this).parent().find(".redditPost").toggleClass("show")
});

Explanation:

$("div[class*='info'])

Handles click for every div with a class containing the string 'info'

$(this).parent().find(".redditPost")

Gets the redditPost class of the current clicked div

答案 2 :(得分:1)

由于class属性可以有多个以空格分隔的类,因此您希望将.filter()方法与RegEx一起使用来缩小元素选择范围,如下所示:

&#13;
&#13;
$('div[class*="info"]').filter(function() {
    return /\binfo\d+\b/g.test( $(this).attr('class') );
}).on('click', function() {
    $(this).siblings('.redditPost').toggleClass('show');
});
&#13;
.show {
  display:none;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="listrow news">
    <div class="newscontainer read">
        <div class="info1">1</div>
        <div class="redditThumbnailinfo">2</div>
        <div class="articleheader read">3</div>
        <div class="redditPost mediumtext">4</div>
    </div>
</div>
&#13;
&#13;
&#13;