jQuery Selector inside of variable?

我们两清 提交于 2019-12-21 09:03:24

问题


Hi I'm trying to get the IDs of all DIVs, inside another HTML File, with a specific Class. To load the file I use:

$.get("blocks.html", function(data) {
        //here I don't know how :)
});

Now what I'm looking for ist something like this:

data.$('.block').each(... the rest is no problem

so that I use the jQuery selectors not on my page code but instead inside the contend of the data variable. Thanks for help!


回答1:


$.get("blocks.html", function(data) {
    var ids = $('<div/>').html(data).find('div.block').map(function() {
        return this.id;
    }).get();
});



回答2:


Try this:

$.get("blocks.html", function(data) {
        $(data).find('.block').each(function(){...});
});

If your 'data html' containing element is a '.block', look at @undefined's answer




回答3:


The answer really depends on what the responseText looks like that is being returned from the GET request. Based on that you would have to wrap it or not.

With Parent

If the response is nested inside of a parent tag.

Response Mark Up:

<div>
   <div id="someId1"></div>
   <div id="yourId" class="block"></div>
   <div id="someId2"></div>
</div>

JavaScript:

var htmlFiltered = $(html).find('.block');

Without Parent

If the response does not have a parent node wrapping the content, you would need to add the parent node or use filter.

Response Mark Up:

<div id="someId1"></div>
<div id="yourId" class="block"></div>
<div id="someId2"></div>

JavaScript:

var htmlFiltered = $(data).filter('.block');

or

var htmlFiltered = $("<div/>").html(data).find('.block');

Getting the ids

You can than use map() or each() on htmlFiltered to get the ids.

With each()

var ids = [];
htmlFiltered.each( function () {
 ids.push(this.id);   
});
console.log(ids);

With map()

var ids = $.map(htmlFiltered, function (elem) {
 return elem.id;   
});
console.log(ids);



回答4:


try:

$.get("blocks.html", function(data) {
        $(data).find('.block').each(...
});


来源:https://stackoverflow.com/questions/16590824/jquery-selector-inside-of-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!