jquery条件不适用于所选属性

时间:2018-01-30 16:42:17

标签: javascript jquery html css html5

我尝试使用第一个选择选项作为值为空的占位符,但它工作正常但问题是我根据用户的选择删除按钮中的禁用类,它是'不工作当我从选项中删除所选属性时,它可以工作,然后不会将第一个选项显示为占位符。 Html代码



$(document).ready(function() {
  $("select").change(function() {
    if ($("#situation").val() != "") {
      $("#calculate").removeClass("disabled");
    } else {
      $("#calculate").addClass("disabled");
    }
  });
  $("select").change();
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="situation">
  <option value="" class="placeholder" selected disabled>Choose</option>
  <option value="1">Live only</option>
  <option value="2">Living together</option>
</select>
<a href="#" id="calculate" class="btn disabled">Calcualte</a>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:2)

问题是因为无法读取disabled option元素的null,因此jQuery返回"",而不是if,因为您的代码是检查。

要解决此问题,您可以更改条件以使用jQuery的虚假性质。您还可以将toggleClass()条件更改为单个$(document).ready(function() { $("#situation").change(function() { $("#calculate").toggleClass("disabled", !$(this).val()); }).change(); });来电,如下所示:

&#13;
&#13;
.disabled {
  color: #CCC;
  pointer-events: none;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="situation">
  <option value="" class="placeholder" selected disabled>Choose</option>
  <option value="1">Live only</option>
  <option value="2">Living together</option>
</select>
<a href="#" id="calculate" class="btn disabled">Calcualte</a>
&#13;
public static void openTelegram(Activity activity, String userName) {
    Intent general = new Intent(Intent.ACTION_VIEW, Uri.parse("https://t.com/" + userName));
    HashSet<String> generalResolvers = new HashSet<>();
    List<ResolveInfo> generalResolveInfo = activity.getPackageManager().queryIntentActivities(general, 0);
    for (ResolveInfo info : generalResolveInfo) {
        if (info.activityInfo.packageName != null) {
            generalResolvers.add(info.activityInfo.packageName);
        }
    }

    Intent telegram = new Intent(Intent.ACTION_VIEW, Uri.parse("https://t.me/" + userName));
    int goodResolver = 0;
    // gets the list of intents that can be loaded.
    List<ResolveInfo> resInfo = activity.getPackageManager().queryIntentActivities(telegram, 0);
    if (!resInfo.isEmpty()) {
        for (ResolveInfo info : resInfo) {
            if (info.activityInfo.packageName != null && !generalResolvers.contains(info.activityInfo.packageName)) {
                goodResolver++;
                telegram.setPackage(info.activityInfo.packageName);
            }
        }
    }
    //TODO: if there are several good resolvers create custom chooser
    if (goodResolver != 1) {
        telegram.setPackage(null);
    }
    if (telegram.resolveActivity(activity.getPackageManager()) != null) {
        activity.startActivity(telegram);
    }
}
&#13;
&#13;
&#13;