所以这个问题在网上被问了很多,我看到的答案是检查。length是否> 0。
所以在我的例子中,选择框可能存在也可能不存在。如果它存在,它可能没有选择。
我必须为以下内容编码:
如果selectbox存在…如果没有选择框选项…禁用文本区
因此我写了以下内容:
$(document).ready(function () {
"use strict";
alert('running globals');
// Only process this block if the contactEmailAddress select box exists
if ($('contactEmailAddress').length > 0) {
alert('on the comm page');
// If there are no contacts ...
if ($('#contactEmailAddress option').size() === 0) {
alert('disabling the message box');
$('#message').attr("disabled", "disabled");
}
}
});
问题是,因为选择框没有选项,它决定了选择框。长度为0。所以这个block永远不会触发。
我需要另一种方法。
您错过了第一个$
的"ID选择器",而是搜索命名为 contactEmailAddress
的元素,而不是ID为contactEmailAddress
的元素。
if ($('#contactEmailAddress').length > 0) {
注意,您可以直接执行$('#contactEmailAddress option').size()
,而不必担心选择是否存在;不会抛出异常或错误。
您可以使用纯javascript来确定元素是否存在。
if( document.getElementById("contactEmailAdress") )
或
if( document.getElementsByClassName("option")[0] )