javascript - 如果元素的后代包含特定单词,则执行代码的 Jquery

标签 javascript jquery html

HTML:

<div id="firstpanel">
    <table class="table table-bordered">
        <tr>
            <td class="alert alert-error">
                <span class="errorMsg">Required:</span>
                blah blah
            </td>
        </tr>
    </table>
</div>
<div id="second panel">
    some text
</div>

如果 firstpanel div 包含单词“Required”,我想执行一些代码

以下代码对我不起作用:

if($("#firstpanel").contains("Required")){

      //some code


 }

最佳答案

您需要使用 :contains() 选择器

if($('#firstpanel:contains("Required")').length){

      //some code

}

:contains() : The matching text can appear directly within the selected element, in any of that element's descendants, or a combination thereof. As with attribute value selectors, text inside the parentheses of :contains() can be written as a bare word or surrounded by quotation marks. The text must have matching case to be selected. ( Taken from https://api.jquery.com/contains-selector/ )

关于javascript - 如果元素的后代包含特定单词,则执行代码的 Jquery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32748027/

相关文章:

php - 网络中的编码问题是如何解决的

javascript - 通过HTTP从浏览器向服务器流式传输数据的方法

javascript - jQuery keyUp/AJAX 获取组合总是落后 1 或 2 笔画

jquery - 在 jQuery UI 对话框中显示复选框并提供取消按钮

javascript - 在 for 循环中创建 <div> 元素时乱序

javascript - 按值对 Javascript 对象进行排序

javascript - 使用 javascript 使用向上和向下箭头键访问 Div 内容

html - CSS 垂直间距问题(边距?)- 两个 Div 之间的垂直间距

javascript - 如何在 UI 列表中单击按钮时使用颜色获取多个值?

javascript - Javascript音频功能不起作用