Javascript仅适用于页面上的某些位置

时间:2022-09-15 08:48:41

I added the javascript code directly into the html, so you are able to see what I am doing wrong.

我将javascript代码直接添加到html中,因此您可以看到我做错了什么。

The alert only works on the img in the div class='sandbar-one' nowhere else.

警报仅适用于div class ='sandbar-one'中的img。

The html ouptut looks like this:

html ouptut看起来像这样:

<html>
  <head> … </head>
  <body>
    <div class="header">
      <div class="sandbar">
        <a style="display:block" href="/">
          <div class="sandbar-logo">
            <div class="sandbar-one">
              <img width="300" src="/assets/123456.png" alt="123456"></img>
            </div>
          </div>
        </a>
        <div class="sandbar-left"> … 
      </div>
    </div  
    <div class="navbar navbar-inverse navbar-fixed-top"> … </div>
  </div>
  <div class="content" data-target="#sidenavbar" data-spy="scroll">
    <div class="container-fluid">
      <div class="row-fluid">
        <div class="span3"> … </div>
      <div class="span9">
        <script>
          $("img").hover(function() {
           alert("Hello World!");
           },function() {
           }) 
        </script>
        <img src="/assets/123456.png" alt="123456"></img>
        ...

the haml file:

haml文件:

:javascript
  $("img").hover(function() {
        alert("Hello World!");
  },function() {
  });

= image_tag("/assets/123456.png")

I tested in Firefox and Safari. The web-console shows no errors.

我在Firefox和Safari中测试过。 Web控制台显示没有错误。

1 个解决方案

#1


3  

This looks to be because when the javascript is executed, only that one img is loaded in the doc. Try executing the JS on page load instead

这看起来是因为当执行javascript时,只有一个img被加载到doc中。尝试在页面加载时执行JS

$(function(){
  $("img").hover(function() {
        alert("Hello World!");
  },function() {
  });
});

#1


3  

This looks to be because when the javascript is executed, only that one img is loaded in the doc. Try executing the JS on page load instead

这看起来是因为当执行javascript时,只有一个img被加载到doc中。尝试在页面加载时执行JS

$(function(){
  $("img").hover(function() {
        alert("Hello World!");
  },function() {
  });
});