jQuery: 根据所选选项显示/隐藏元素

3

当选项 value='Attached File' 被选中时,我希望显示元素的 id=attach。请帮助我理解为什么我的代码不起作用。

我的代码:

<ul class="form-list">
  <li id="excellence-form">
    <fieldset>
      <ul>
        <li class="wide">
          <label for="excellence:like" class="required"><em>*</em><?php echo $this->__('Initial Data') ?></label>
          <div class="input-box">
            <select class="required-entry" name="excellence[like]" id="excellence:like">
              <option value='0'><?php echo $this->__('Please Choose..');?></option>
              <option value='Not Attached' <?php if($this->getQuote()->getExcellenceLike() == 1){echo 'selected="selected"';} ?>><?php echo $this->__('Do Not Attach File');?></option>
              <option value='Attached File' <?php if($this->getQuote()->getExcellenceLike() == 2){echo 'selected="selected"';} ?>><?php echo $this->__('Attach File');?></option>
            </select>
          </div>
        </li>
        <li id="attach" style="display:none;" >
          <label class="required"><em>*</em><?php echo $this->__('Please Attach :') ?><span id='file_upload_text'></span></label>
          <div class="input-box">
            <input id="file_upload" type="file" name="file_upload" />
          </div>
          <input id="file_upload_path" type="hidden" name="file_upload_path" class='required-entry' />
          <input type="hidden" value='Attached File' name="file_upload_type" class='required-entry' />
        </li>
      </ul>
    </fieldset>
  </li>
</ul>

我的jQuery:

<script type="text/javascript">
  $(function() {
    $('#excellence:like').change(function(){
      if ($(this).val() == "Attached File") {
        document.getElementById("attach").style.display="block";
      } else {
        document.getElementById("attach").style.display="none";
      }
    });
  });
</script>

2
#excellence:like jQuery 可能不喜欢这个ID,因为CSS和jQuery都使用“:”表示伪类等。尝试使用 #excellence-like 这样的写法。 - Andy
为什么你不使用$('#attach')来代替document.getElementById,而不是.show()或.hide()? - cptnk
3个回答

2

由于":"是css选择器的一部分,因此应避免使用它。

尝试这个...

$(function() {      
    $('.required-entry').change(function(){    // use class or use $('select')
        if ($(this).val() == "Attached File") {
            $("#attach").show();
        } else {
             $("#attach").hide();
        }
    });
});

1

你需要在ID中转义:(或使用


1

try this one

$(function() {
    $('#excellence\\:like').change(function(){
        if ($(this).val() == "Attached File") {
            $("#attach").show();
        } else {
             $("#attach").hide();
        }
    });
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接