One Two

Limit the number of elements from an AJAX response

AJAX response returns a list of <a> elements:

 <a href="/1/">One</a> <a href="/2/">Two</a> <a href="/3/">Three</a> 

How to select only the first n a elements from the answer?

 $.ajax({ url: '/' + page, success: function (res) { btn.after($('a', $(res)).slice(0,20)); } }); 

What I'm trying now, but getting Uncaught Error: Syntax error, unrecognized expression , followed by the whole answer.

+6
source share
3 answers

The answer had two closing div elements at the end, but there were no two holes, so I had to make one:

 $.ajax({ url: '/' + page, success: function (res) { btn.after($('a', $($.trim('<div><div>'+res))).slice(0,20)); } }); 
+1
source

Here is what I would do:

 $.ajax({ url: '/' + page, success: function (res) { btn.after(res.split('</a>').splice(0, num).join('</a> ') + '</a>'); } }); 

It breaks it and returns only those elements that you want.

JSFiddle: http://jsfiddle.net/howderek/VamZt/

0
source

The problem is that the context selector does not return anything. A simple test shows this.

 console.log($('a', $(res))) 

Break it into pieces. You need to use a filter for content that is returned from the server, because this is a list of anchors.

 var content = $(res); var anchors = content.filter("a"); var anchorLimit = anchors.slice(0,20); btn.after(anchorLimit); 

Another option is to do what you did, but wrap it in a div.

 $('a', $("<div>" + res + "</div>")) 

Jsfiddle

0
source

Source: https://habr.com/ru/post/959394/


All Articles