【问题标题】:jQuery selector dont work?jQuery 选择器不起作用?
【发布时间】:2013-05-23 00:42:27
【问题描述】:

嗨,我开始学习 jquery,我阅读了教程并构建了我的代码,但我想知道为什么这段代码在我的页面上不起作用:

<script src="jquery-1.9.1.js"></script>  
<script src="jquery-ui.js"></script>
<script src="jquery-min.js"></script>
<script type="text/javascript">
  $("#storage").change(function(){
    alert("sample ng onchange");    
  });
</script>


<tr><td><s:text name="label.storageArea" /></td>
<td><s:select  name="mediaBean.storageAreaDesc" 
            list="storageAreaList"              
            value="%{mediaBean.storageAreaDesc}" 
            size="1" style="width:155px;" 
            theme="simple" id="storage" />
</td>   
</tr>

请帮忙。谢谢。

下面是标签的 HTML:

<select name="mediaBean.storageAreaDesc" size="1" id="storage" style="width:155px;">
    <option value="1 - Storage 1" selected="selected">1 - Storage 1</option>
    <option value="2 - Storage 2">2 - Storage 2</option>
    <option value="3 - Storage 3">3 - Storage 3</option>
</select>

【问题讨论】:

  • 您需要使用文档就绪处理程序。 api.jquery.com/ready
  • 除此之外,&lt;s:select&gt; 不是标准的 HTML 元素,如果它显示在页面中,是否支持通过 ID 选择它可能取决于浏览器对这些东西的松懈程度。如果您的框架在运行时扩展了元素,您可能希望显示生成的 HTML。

标签: jquery jquery-selectors struts2


【解决方案1】:

因为您的脚本 在 HTML 之前,请将其包含在 DOM ready handler 中。这可以确保脚本在 DOm 加载后运行。

<script type="text/javascript">
  $(function() {
      $("#storage").change(function(){
         alert("sample ng onchange");    
      });
   });
</script>

【讨论】:

  • 这是否意味着HTML之后的脚本保证在DOM加载后执行?
【解决方案2】:

也许你需要将你的 js 代码包装在一个 jquery 文档就绪块中

http://api.jquery.com/ready/Jquery select change

【讨论】:

  • 对不起,我无法接受两个答案,但您的解决方案也是正确的。感谢您的回复!
【解决方案3】:

首先,将你所有的 js 放在页面底部,并用它来包装你的代码

;(function($) {
    $(document).ready(function() {
        // Stuff to do as soon as the DOM is ready. 
        // Use $() w/o colliding with other libs;
    })
})(jQuery);

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-12-19
  • 2015-03-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-02
  • 1970-01-01
相关资源
最近更新 更多