遍历变量中的元素 [英] Loop through elements in a variable

查看:85
本文介绍了遍历变量中的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何遍历存储在"ul"标签变量中的HTML?到目前为止,这就是我所拥有的,但是alert()甚至都没有触发,我有点迷失了……

How would loop through HTML stored in a variable for 'ul' tags? This is what I have so far but the alert() don't even trigger, Im a bit lost...

var data = 'HTML';
$('ul', data).each(function(i,v) {
    var theTag = v.tagName;
    var theElement = $(v);
    var theValue = theElement.html();
    alert(theTag+'\n'+theElement+'\n'+theValue);
});

谢谢

推荐答案

您正尝试使用

You're trying to use the "selector, context" form of the $() call:

jQuery(选择器[,上下文])
选择器包含选择器表达式的字符串
context 用作上下文的DOM元素,文档或jQuery

jQuery( selector [, context] )
selector A string containing a selector expression
context A DOM Element, Document, or jQuery to use as context

HTML字符串与context应该具有的任何条件都不匹配,因此jQuery不知道如何处理您的参数并做出错误的猜测.

A string of HTML doesn't match any of the things that context is supposed to be so jQuery doesn't know what to do with your arguments and makes the wrong guess.

您可能想要这样做:

$(data).filter('ul').each(function(i,v) {
    //...
});

演示: http://jsfiddle.net/ambiguous/gxGB8/

或者,如果您不知道<ul>元素的级别,则将HTML包裹在<div>中,然后使用 find代替 filter :

Or, if you don't know at what level the <ul> elements will be, wrap the HTML in a <div> and use find instead of filter:

$('<div>' + data + '</div>').find('ul').each(function(i, v) {
    //...
});

演示: http://jsfiddle.net/ambiguous/tM4ua/

这篇关于遍历变量中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆