简体   繁体   English

为什么这个jQuery选择器不返回任何元素?

[英]Why is this jQuery selector not returning any elements?

I am trying to select all sub-elements and filter those with certain attributes. 我试图选择所有子元素并过滤具有某些属性的子元素。 One of the elements is a contenteditible div that contains a data-required attribute(see HTML below). 元素之一是可内容编辑的div,其中包含数据所需的属性(请参见下面的HTML)。 When I use the following selector, it returns 1: 当我使用以下选择器时,它返回1:

$("#mail-container").filter('[required], [data-required]').length

But when I execute the following, 0 is returned: 但是,当我执行以下命令时,将返回0:

form.contents().filter('[data-required]').length;

Note, the following returns 9: 注意,以下返回9:

form.contents().length;

EDIT 编辑

The following function is called as follows: 调用以下函数:

$("#send-email").on('mouseup', function (e) {
    if (!validateRequiredFields($("#form-email-preview"))) return false;
    var data = {};
    data.action = "manuscript-request-email";
    data["writers-id"] = $("#writer-id").val();
    data["account-id"] = localStorage.getItem("account-id");
    data.subject = $("#subject").val();
    data.body = $("#mail-container").html();
    ajax('post', 'php/writers.php', data, sentEmail);
    function sentEmail(result) {
        console.log("email-res=" + result);
        return2table();
    }
});

function validateRequiredFields(form) {
    var $reqFlds = form.contents().filter('[required], [data-required]');
    var ret = true;
    debugger
    $reqFlds.each(function() {
        var $this = $(this);
        var result = ($this.eq("input, select, textarea")) ? $this.val() : $this.text();
        if (!$.trim(result)) {
            $this.prop('data-toggle=popover', true);
            $this.show();
            $this.popover("destroy").popover({ content: "Please fill out this field.", placement: 'bottom' });
            $this.popover('show');
            $this.focus();
            ret = false;
            return false;
        }
    });
    return ret;
}

HTML HTML

<form id="form-email-preview" style="margin-top: 24px;">
    <div id="main-container" class="hidden" style="border: 1px solid black; padding: 6px;  border-radius: 8px;">
        <span><b>Subject:</b></span><input id="subject" type="text" value="Manuscript Request" style="display: inline-block" />
        <p><b>Email:</b></p>
        <div id="mail-container" contenteditable data-toggle="popover" data-required data-placement="top" data-title ="Required field" style="display: inline-block"></div><br/>
        <p id="buttons" class="hidden">
            <input type='button' id='send-email' class='btn btn-custom-success' value='Send Email' /><span>   </span>
            <button id='cancel-email' class = 'btn btn-danger'>Cancel</button>
        </p>
    </div>
    <div id="current-row" class="hidden"></div>
    <input id="current-checkbox" type="checkbox" class="hidden" />
    <input id="current-tr" type="number" class="hidden" />
</form>

What am I missing? 我想念什么?

There simply are no matching elements ? 根本没有匹配的元素?

In this context, you're doing 在这种情况下,您正在做

validateRequiredFields( $("#form-email-preview") );

function validateRequiredFields(form) {

    var $reqFlds =  form.contents().filter('[required], [data-required]');

    ....

form.contents() gets you the nine children of the form, that's including the textnodes form.contents()您提供表单的九个子form.contents() ,其中包括textnodes

<form id="form-email-preview" style="margin-top: 24px;">
    <!-- text node here -->                                           <!-- 1 -->
    <div id="main-container" ...></div>                               <!-- 2 -->
    <!-- text node here -->                                           <!-- 3 -->
    <div id="current-row" class="hidden"></div>                       <!-- 4 -->
    <!-- text node here -->                                           <!-- 5 -->
    <input id="current-checkbox" type="checkbox" class="hidden" />    <!-- 6 -->
    <!-- text node here -->                                           <!-- 7 -->
    <input id="current-tr" type="number" class="hidden" />            <!-- 8 -->
    <!-- text node here -->                                           <!-- 9 -->
</form>

That's nine, none of them are the elements you're looking for, and here's what contents() does 那是九个,它们都不是您要查找的元素,这是contents()作用

Get the children of each element in the set of matched elements, including text and comment nodes. 获取匹配的元素集中每个元素的子元素,包括文本和注释节点。

Then you filter those nine elements, and only those nine, as filter() doesn't filter children of those nine, only those 然后,您过滤了这九个元素,并且仅过滤了这九个元素,因为filter()不会过滤这九个元素的子对象,而仅filter()那些

Reduce the set of matched elements to those that match the selector or pass the function's test. 将匹配元素的集合减少到与选择器匹配或通过功能测试的元素。

You have a set of nine elements, none of them with the attributes you're looking for, and you filter that set, and you end up with ... nothing 您有一组九个元素,没有一个具有您要查找的属性,然后过滤该集合,最后得到的结果是……什么都没有

What you wanted was just 你想要的只是

var $reqFlds = form.find('[required], [data-required]');

As a sidenote, read the documentation for the methods you're using, and it should be clear what they do, for instance these are incorrect 作为旁注,请阅读所用方法的文档,并应清楚它们的作用,例如,这些方法不正确。

$this.eq("input, select, textarea") // eq() accepts a number only

$this.prop('data-toggle=popover', true); // accepts a property, 
                                         // not an entire attribute, with the value ?

Based on the example code without any context, it looks like form represents a DOM node instead of a jQuery object. 基于没有任何上下文的示例代码,它看起来像form代表了DOM节点而不是jQuery对象。

Just wrap it in the jQuery method to make it a jQuery object then it should work fine. 只需将其包装在jQuery方法中以使其成为jQuery对象,然后它就可以正常工作。

var $reqFlds = $(form).contents().filter('[required], [data-required]');

not sure if this is the cause of your problem but in the first example you are using the $("#mail-container") element. 不知道这是否是导致问题的原因,但是在第一个示例中,您使用的是$(“#mail-container”)元素。 In your code (!validateRequiredFields($("#form-email-preview"))) you referring to the $("#form-email-preview") element. 在您的代码(!validateRequiredFields($(“#form-email-preview”)))中,您指的是$(“#form-email-preview”)元素。 I hope it helps 希望对您有所帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM