简体   繁体   中英

Detect if two elements have the same ID on a page

On page load, 5 items are selected from the database. As the user scrolls down, 5 more posts are loaded, etc.

To prevent duplicate posts when sorting by 'new', I place the page load time in a hidden input to be used in JavaScript:

<input id="loadTime" type="hidden" value="<?php echo time(); ?>">

Then when fetching more posts while scrolling I only select new ones from before that time to prevent duplicate posts.

WHERE s.date < :loadTime

However, my issue is when sorting by Hot or Top, because it doesn't use the same logic.

Is it possible to detect if two elements on the page have the same ID? Because when a duplicate post is appended to the page, it will have the same ID as one already on it. Some sort of $(window).scroll() have a function that removes the duplicate ID afterwards so that the user doesn't see duplicate posts?

I was able to solve it:

In the success function after I append the new posts, I loop through all the IDs on the page (taken from this answer then remove the last element with that id.

$('[id]').each(function(){
    var ids = $('[id="'+this.id+'"]');
        if (ids.length>1 && ids[0]==this){
            $("#"+this.id).last().remove();
        }
 });

How about instead of passing the initial load time with the JavaScript request, store and send the ID of the last post you received in the previous group of 5?

Your server-side logic can then (in a transaction) read out the "hotness" or "topness" or creation date, or whatever value you're sorting by, of the last post that the user has seen, before selecting the 5 next posts with a value less than that post's value.

►Is it possible to detect if two elements on the page have the same ID?

It is possible to find elements with duplicate Id. You can use selection with attribute id .

DEMO

 if($('[id="same"]').length > 1){ alert("duplicate id") } // To remove last inserted element with duplicate ID $('[id="same"]').last().remove() 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text" id="same"> <input type="text" id="same"> <input type="text" id="same"> <input type="text" id="same" value="Last element"> 

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