使用javascript .onclick函数的正确方法是什么?

时间:2019-01-22 08:58:27

标签: javascript html onclick

使用.onclick运行函数时,它没有执行。我做错了什么吗?

<script>
  const object1 = document.getElementById('object1');
  const image2Path = "image2.svg";

  object1.onclick = () => {
    object1.src = image2Path;
  }
</script>
<body>
  <img id='object1' src="image1.svg">
</body>

我希望单击该对象时image1(成功显示)会变为image2。

2 个答案:

答案 0 :(得分:0)

您需要正确绑定onclick处理程序。这将是一种方法:

<script>
  function toogle()
  {
     const object1 = document.getElementById('object1');
     const image2Path = "image2.svg";

     object1.src = image2Path;
  }
</script>
<body>
  <img id='object1' src="image1.svg" onclick="toggle();">
</body>

答案 1 :(得分:0)

<properties>
    <drools.version>6.3.0.Final</drools.version>
    <java.version>1.8</java.version>
</properties>


<dependencies>
    <dependency>
        <groupId>org.drools</groupId>
        <artifactId>drools-core</artifactId>
        <version>${drools.version}</version>
    </dependency>


    <dependency>
        <groupId>org.drools</groupId>
        <artifactId>drools-compiler</artifactId>
        <version>${drools.version}</version>
    </dependency>

    <dependency>
        <groupId>org.kie</groupId>
        <artifactId>kie-api</artifactId>
        <version>${drools.version}</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.kie.server/kie-server-api -->
    <dependency>
        <groupId>org.kie.server</groupId>
        <artifactId>kie-server-api</artifactId>
        <version>${drools.version}</version>
    </dependency>

</dependencies>

<build>
    <plugins>

        <plugin>
            <groupId>org.kie</groupId>
            <artifactId>kie-maven-plugin</artifactId>
            <version>${drools.version}</version>
            <extensions>true</extensions>
        </plugin>

        <plugin>
            <!-- Build an executable JAR -->
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-jar-plugin</artifactId>
            <version>3.1.1</version>
            <configuration>
                <archive>
                    <manifest>
                        <mainClass>App</mainClass>
                    </manifest>
                </archive>
            </configuration>
        </plugin>
    </plugins>
</build>
  const object1 = document.getElementById('object1');
  const image2Path = "image2.svg";

  object1.onclick = () => {
    object1.src = image2Path;
  }