if语句jQuery中的多个条件

时间:2016-05-25 20:15:32

标签: javascript jquery if-statement

我想继续(因为内容是通过AJAX接收的)检查是否存在具有电子邮件类名的输入,并且是否存在以显示具有上传类名的另一输入并且如果此输入存在并且另一输入具有点击按钮的类名来做某事。

我已经设法连续检查是否存在具有电子邮件类名的输入,并且是否存在以显示具有上传类名的输入,但我不知道如何继续此操作。

这是我到目前为止所做的:

(function(doc,found) {
var observer = new MutationObserver(function(mutations) {
    mutations.forEach(function(mutation) {

      var mydiv = doc.querySelector("input.email");

      if(found && !mydiv){
        // Was there but is gone, do something
        found = false;
        $('input.upload').hide();

      }

      if(mydiv){
        // Found it, do something
        found = true;
        $('input.upload').show();

      }

    });
});
observer.observe(doc, { childList: true, subtree: true });
})(document,false);

1 个答案:

答案 0 :(得分:2)

您正在使用jQuery,但也使用document.querySelector()。最好是保持一致并一直使用jQuery,或者直接使用DOM方法而不使用jQuery。

使用.toggle()可以更加简洁地显示/隐藏代码。

(function(doc) {
    var observer = new MutationObserver(function(mutations) {
        // You don't need to iterate over the mutations, 
        // and showing/hiding the upload input can be done with a one-liner:
        $('input.upload').toggle($("input.email").length>0);
    });
    observer.observe(doc, { childList: true, subtree: true });
    // Here is the click handler. It checks for the existence of the input.
    $('input.button').click(function() {
        if ($('input.email').length) {
            alert('There is an email input. We could do something.');
        } else {
            alert('No email input present');
        }
    });
})(document);

// Simulate a mutation that removes/adds an `input.email` control on button click
$('#toggle').click(function() {
    if ($('input.email').length) {
        $('input.email').remove();
    } else {
        $('<input class="email"  type="text">').insertBefore($('br')[0]);
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Email:  <input class="email"  type="text"><br>
Upload: <input class="upload" type="file"><br>
<input class="button" type="button" value="button"><br>
<hr>
Click this button to trigger a mutation concerning email input:<br>
<button id="toggle">Create/Delete email input</button>

关于MutationObserver的警告

听取MutationObserver事件时必须小心。如果在事件处理程序中您进行了另一次突变,则会触发一个新事件,您可能会进入无限循环。

即使上面的代码也存在风险:toggle方法将改变元素的可见性,jQuery将通过设置display CSS样式来实现。但这是对文件的修改!因此触发了另一个突变事件,并再次调用toggle方法。幸运的是,当jQuery发现可见性已经正确设置时,jQuery不会改变文档 - 这是第二次调用的情况 - 因此不会触发进一步的突变事件。