简体   繁体   中英

Get every ID from every DIV with a specific class

I'm working on a website which has multiple news articles in it's homepage. I have a function which removes letters if the news article contains more than 300 characters. A hyperlink "read more" will show up so the reader can read the full article. Once the reader clicks on Read More, he/she will be redirected to a link containing the article ID in it. For example: index.php?newsid=73

However, I need to give every DIV the ID of the ID of the news article. This isn't really much of a problem, the problem is: How would I get jQuery to get the ID of the div to give every hyperlink it's own URL?

My current code:

        $(document).ready(function(){
    var myDiv = $('.content');
    var abc = $(this).closest(".content").attr("id");
        //var myDiv = $('.content').attr('class');
        //var myDiv = $('#content');
        //myDiv.html(myDiv.text().substring(0,300) + '<a href="#">Read more</a>');
    })(jQuery);

I commented a couple of lines just to test it. My code obviously doesn't work and I am kinda lost. This is how I give every div it's own ID:

echo "<div class='content' id='" .$myrow['id'] ."'>" .$myrow['content']. "</div>";

Use jquery's .map() function

var arr = $('.content').map(function (i) {
    return this.id;
});

The resulting array arr will contain the ids.

Use each loop ?

$(function(){
   $('.content').each(function(){
      var _this=$(this);
      // use _this now to get each items/It's internal properties /items
      var textContent=_this.text();
      //Do your substring function here and set the text back to the item
      _this.text("Put your updated text here");
   });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM