jQuery - 如何将 AND 与选择器一起使用?

jQuery - How do I use AND with Selector?

我的代码的功能是在 ptype 文本字段为空时提醒用户。

$("input[name*='ptype']").each(function() {
                if ($(this).val() == "") {
                    $(this).css({'background-color' : '#feffe3'});
                    e.preventDefault();
                    alert("Enter Value!");
                }
            });

但是,我需要在另一个字段 amount 不为 0 的地方添加另一个条件。以便在 ptype="" && amount!=0 时触发函数。我是 jQuery 的新手,我不确定如何在这里使用 AND 运算符。我试着根据其他问题做了一些,但似乎没有用。

$("input[name*='ptype'][amount!='0']").each(function() {

$("input[name*='ptype'] , [amount!='0']").each(function() {

我错过了什么?

&&符号就可以了。代码取决于您的金额字段所在的位置以及它是什么。如果我猜对了应该是这样的:

$("input[name*='ptype']").each(function() {
                if ($(this).val() == "" && $(this).parent().find(input[name='amount']).val() != 0) {
                    $(this).css({'background-color' : '#feffe3'});
                    e.preventDefault();
                    alert("Enter Value!");
                }
            });

该代码 $("input[name*='ptype'][amount!='0']").each(function() { 有效。您必须检查 CSS selectors list.

问题可能出在您的 *= 选择中。 input[name*="ptype"] 表示选择 name 属性值包含子字符串 "ptype".

的每个元素
$('input[name*="ptype"][amount!="0"]').each(function() {
                if ($(this).val() == "") {
                    $(this).css({'background-color' : '#feffe3'});
                    e.preventDefault();
                    alert("Enter Value!");
                }
            });

看看这个测试https://jsfiddle.net/xpvt214o/211871/

您可以在您的按钮中使用此功能。

function check(e){

    var verror = false;

    $("input[name*='ptype']").each(function(index, value) {
        var amount = $($("input[name='amount[]']").get(index)).val();
        var ptype = $(this).val();
        if(ptype.length <= 0 && amount.length > 0 ){
            verror = true;
            $(this).focus();
            return false;
        }
    });

    if(verror){
        e.preventDefault();
        alert("Enter Value!");
    }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form>
    ptype: <input type="text" name="ptype[]">
    amount: <input type="text" name="amount[]" value="1"> <br>

    ptype: <input type="text" name="ptype[]">
    amount: <input type="text" name="amount[]" value="2"> <br>

    <button type="button" onclick="check(event)">Click</button>
</form>

« 其中另一个字段» 是有问题的关键。

因此您需要一个选择器来检查所选元素是否为空并且另一个元素不为零。

你好!

这里逻辑有问题。 使用 $(selector) 您可以查找一些元素。

多组匹配元素的选择器中没有 AND / OR。
一个选择器是 ONE 组匹配元素。

此选择器无法检查另一组的属性 value

所以您必须了解您的标记并稍微导航一下...并且注意变量类型。

$("input[name*='ptype']").each(function() {
  if ( parseInt( $(this).next("input").val() ) != 0) {
    $(this).css({"background-color" : "red"});
    alert("Enter Value!");
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

ptype: <input type="text" name="ptype"><br>
amount: <input type="text" name="amount" value="1">

根据我的理解,您必须在此处寻找另一个元素的值。所以你必须知道 "other" 元素是什么,使用的方法可能会因你的 HTML...

而有很大不同