jQuery.each - 在 ul 中获取 li 元素

发布于 2024-11-07 15:58:04 字数 962 浏览 1 评论 0原文

我的页面上有这个 HTML:

<div class="phrase">
    <ul class="items">
        <li class="agap"><ul><li>TEXT1</li></ul></li>
        <li class="agap"><ul>  </ul></li> <!-- empty ul -->
        <li class="aword">TEXT2</li>
        ..
    </ul>
</div>

<div class="phrase"> ... </div>

我想为每个“短语”获取文本变量中“items”中的所有元素,如下所示:

var string = "TEXT1 - BLANK - TEXT2";

我目前有这个 javascript 代码:

<script>
$(function() {
    $('.phrase .items').each(function(){
        var myText = "";

        // At this point I need to loop all li items and get the text inside
        // depending on the class attribute

        alert(myText);

    });
};
</script>

How can I iterate all < li> 位于 .items 内?

我尝试了不同的方法,但没有得到好的结果。

I have this HTML on my page:

<div class="phrase">
    <ul class="items">
        <li class="agap"><ul><li>TEXT1</li></ul></li>
        <li class="agap"><ul>  </ul></li> <!-- empty ul -->
        <li class="aword">TEXT2</li>
        ..
    </ul>
</div>

<div class="phrase"> ... </div>

I would like to get for each "phrase" all the elements in "items" in a text variable, like this:

var string = "TEXT1 - BLANK - TEXT2";

I currently have this javascript code:

<script>
$(function() {
    $('.phrase .items').each(function(){
        var myText = "";

        // At this point I need to loop all li items and get the text inside
        // depending on the class attribute

        alert(myText);

    });
};
</script>

How can I iterate all <li> inside .items?

I was trying different ways but I didn't get good results.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

执妄 2024-11-14 15:58:04

首先,我认为您需要修复列表,因为

    的第一个节点必须是

  • (stackoverflow 参考)。设置完成后,您可以执行以下操作:
// note this array has outer scope
var phrases = [];

$('.phrase').each(function(){
        // this is inner scope, in reference to the .phrase element
        var phrase = '';
        $(this).find('li').each(function(){
            // cache jquery var
            var current = $(this);
            // check if our current li has children (sub elements)
            // if it does, skip it
            // ps, you can work with this by seeing if the first child
            // is a UL with blank inside and odd your custom BLANK text
            if(current.children().size() > 0) {return true;}
            // add current text to our current phrase
            phrase += current.text();
        });
        // now that our current phrase is completely build we add it to our outer array
        phrases.push(phrase);
    });
    // note the comma in the alert shows separate phrases
    alert(phrases);

工作 jsfiddle

一件事是,如果您获得上层 li.text(),您将获得所有子级别文本。

保留一个数组将允许提取许多多个短语。


编辑:

这对于没有 LI 的空 UL 应该效果更好:

// outer scope
var phrases = [];

$('.phrase').each(function(){
    // inner scope
    var phrase = '';
    $(this).find('li').each(function(){
        // cache jquery object
        var current = $(this);
        // check for sub levels
        if(current.children().size() > 0) {
            // check is sublevel is just empty UL
            var emptyULtest = current.children().eq(0); 
            if(emptyULtest.is('ul') && $.trim(emptyULtest.text())==""){
                phrase += ' -BLANK- '; //custom blank text
                return true;   
            } else {
             // else it is an actual sublevel with li's
             return true;   
            }
        }
        // if it gets to here it is actual li
        phrase += current.text();
    });
    phrases.push(phrase);
});
// note the comma to separate multiple phrases
alert(phrases);

First I think you need to fix your lists, as the first node of a <ul> must be a <li> (stackoverflow ref). Once that is setup you can do this:

// note this array has outer scope
var phrases = [];

$('.phrase').each(function(){
        // this is inner scope, in reference to the .phrase element
        var phrase = '';
        $(this).find('li').each(function(){
            // cache jquery var
            var current = $(this);
            // check if our current li has children (sub elements)
            // if it does, skip it
            // ps, you can work with this by seeing if the first child
            // is a UL with blank inside and odd your custom BLANK text
            if(current.children().size() > 0) {return true;}
            // add current text to our current phrase
            phrase += current.text();
        });
        // now that our current phrase is completely build we add it to our outer array
        phrases.push(phrase);
    });
    // note the comma in the alert shows separate phrases
    alert(phrases);

Working jsfiddle.

One thing is if you get the .text() of an upper level li you will get all sub level text with it.

Keeping an array will allow for many multiple phrases to be extracted.


EDIT:

This should work better with an empty UL with no LI:

// outer scope
var phrases = [];

$('.phrase').each(function(){
    // inner scope
    var phrase = '';
    $(this).find('li').each(function(){
        // cache jquery object
        var current = $(this);
        // check for sub levels
        if(current.children().size() > 0) {
            // check is sublevel is just empty UL
            var emptyULtest = current.children().eq(0); 
            if(emptyULtest.is('ul') && $.trim(emptyULtest.text())==""){
                phrase += ' -BLANK- '; //custom blank text
                return true;   
            } else {
             // else it is an actual sublevel with li's
             return true;   
            }
        }
        // if it gets to here it is actual li
        phrase += current.text();
    });
    phrases.push(phrase);
});
// note the comma to separate multiple phrases
alert(phrases);
守望孤独 2024-11-14 15:58:04
$(function() {
    $('.phrase .items').each(function(i, items_list){
        var myText = "";

        $(items_list).find('li').each(function(j, li){
            alert(li.text());
        })

        alert(myText);

    });
};
$(function() {
    $('.phrase .items').each(function(i, items_list){
        var myText = "";

        $(items_list).find('li').each(function(j, li){
            alert(li.text());
        })

        alert(myText);

    });
};
凉风有信 2024-11-14 15:58:04

给出了高票数和观点的答案。我确实通过混合此处和其他链接找到了答案。

我有一个场景,如果未选择患者,所有与患者相关的菜单都会被禁用。 (请参阅链接 - 如何使用 JavaScript 禁用 li 标签

//css
.disabled{
    pointer-events:none;
    opacity:0.4;
}
// jqvery
$("li a").addClass('disabled');
// remove .disabled when you are done

因此,我没有编写长代码,而是通过 CSS 找到了一个有趣的解决方案。

$(document).ready(function () {
 var PatientId ; 
 //var PatientId =1;  //remove to test enable i.e. patient selected
	if (typeof PatientId == "undefined" || PatientId == "" || PatientId == 0 || PatientId == null) {
		console.log(PatientId);
		$("#dvHeaderSubMenu a").each(function () {			
			$(this).addClass('disabled');
		});		
		return;
	}
})
.disabled{
    pointer-events:none;
    opacity:0.4;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="dvHeaderSubMenu">
     <ul class="m-nav m-nav--inline pull-right nav-sub">
						<li class="m-nav__item">
							<a href="#" onclick="console.log('PatientMenu Clicked')" >
								<i class="m-nav__link-icon fa fa-tachometer"></i>
								Overview
							</a>
						</li>

						<li class="m-nav__item active">
							<a href="#" onclick="console.log('PatientMenu Clicked')" >
								<i class="m-nav__link-icon fa fa-user"></i>
								Personal
							</a>
						</li>
            <li class="m-nav__item m-dropdown m-dropdown--inline m-dropdown--arrow" data-dropdown-toggle="hover">
							<a href="#" class="m-dropdown__toggle dropdown-toggle" onclick="console.log('PatientMenu Clicked')">
								<i class="m-nav__link-icon flaticon-medical-8"></i>
								Insurance Claim
							</a>
							<div class="m-dropdown__wrapper">
								<span class="m-dropdown__arrow m-dropdown__arrow--left"></span>
								
											<ul class="m-nav">
												<li class="m-nav__item">
													<a href="#" class="m-nav__link" onclick="console.log('PatientMenu Clicked')" >
														<i class="m-nav__link-icon flaticon-toothbrush-1"></i>
														<span class="m-nav__link-text">
															Primary
														</span>
													</a>
												</li>
												<li class="m-nav__item">
													<a href="#" class="m-nav__link" onclick="console.log('PatientMenu Clicked')">
														<i class="m-nav__link-icon flaticon-interface"></i>
														<span class="m-nav__link-text">
															Secondary
														</span>
													</a>
												</li>
												<li class="m-nav__item">
													<a href="#" class="m-nav__link" onclick="console.log('PatientMenu Clicked')">
														<i class="m-nav__link-icon flaticon-healthy"></i>
														<span class="m-nav__link-text">
															Medical
														</span>
													</a>
												</li>
											</ul>
										
							
						</li>
     </ul>            
</div>

Given an answer as high voted and views. I did find the answer with mixed of here and other links.

I have a scenario where all patient-related menu is disabled if a patient is not selected. (Refer link - how to disable a li tag using JavaScript)

//css
.disabled{
    pointer-events:none;
    opacity:0.4;
}
// jqvery
$("li a").addClass('disabled');
// remove .disabled when you are done

So rather than write long code, I found an interesting solution via CSS.

$(document).ready(function () {
 var PatientId ; 
 //var PatientId =1;  //remove to test enable i.e. patient selected
	if (typeof PatientId == "undefined" || PatientId == "" || PatientId == 0 || PatientId == null) {
		console.log(PatientId);
		$("#dvHeaderSubMenu a").each(function () {			
			$(this).addClass('disabled');
		});		
		return;
	}
})
.disabled{
    pointer-events:none;
    opacity:0.4;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="dvHeaderSubMenu">
     <ul class="m-nav m-nav--inline pull-right nav-sub">
						<li class="m-nav__item">
							<a href="#" onclick="console.log('PatientMenu Clicked')" >
								<i class="m-nav__link-icon fa fa-tachometer"></i>
								Overview
							</a>
						</li>

						<li class="m-nav__item active">
							<a href="#" onclick="console.log('PatientMenu Clicked')" >
								<i class="m-nav__link-icon fa fa-user"></i>
								Personal
							</a>
						</li>
            <li class="m-nav__item m-dropdown m-dropdown--inline m-dropdown--arrow" data-dropdown-toggle="hover">
							<a href="#" class="m-dropdown__toggle dropdown-toggle" onclick="console.log('PatientMenu Clicked')">
								<i class="m-nav__link-icon flaticon-medical-8"></i>
								Insurance Claim
							</a>
							<div class="m-dropdown__wrapper">
								<span class="m-dropdown__arrow m-dropdown__arrow--left"></span>
								
											<ul class="m-nav">
												<li class="m-nav__item">
													<a href="#" class="m-nav__link" onclick="console.log('PatientMenu Clicked')" >
														<i class="m-nav__link-icon flaticon-toothbrush-1"></i>
														<span class="m-nav__link-text">
															Primary
														</span>
													</a>
												</li>
												<li class="m-nav__item">
													<a href="#" class="m-nav__link" onclick="console.log('PatientMenu Clicked')">
														<i class="m-nav__link-icon flaticon-interface"></i>
														<span class="m-nav__link-text">
															Secondary
														</span>
													</a>
												</li>
												<li class="m-nav__item">
													<a href="#" class="m-nav__link" onclick="console.log('PatientMenu Clicked')">
														<i class="m-nav__link-icon flaticon-healthy"></i>
														<span class="m-nav__link-text">
															Medical
														</span>
													</a>
												</li>
											</ul>
										
							
						</li>
     </ul>            
</div>

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文