JS函数未通过onClick调用

时间:2018-10-11 12:20:40

标签: javascript html

我正在尝试调用一个函数,比方说在外部JS脚本中的“ example()”。

脚本/examplefile.js

  function example() {
        console.log('function called');
        // blah blah blah
    }
    console.log('JS file was run');
    <html>
        <head>
            <script src='Scripts/examplefile.js'></script>
        </head>
        <body>
            <button type='button' onClick='example()'>Click me</button>
        </body>
    </html>

控制台不会打印“ JS文件已运行”,但该按钮什么也不做。

//编辑// 解: 我实际的JS函数名称是'checkValidity',它不受支持或不合法。不确定。我将其更改为其他内容,并且可以正常工作。

问题重新创建:

    <html>
        <head>
            <script>
                function checkValidity() {
                    console.log('function called');
                }
                console.log('jsok');
            </script>
        </head>
        <body>
            <button type='button' onClick='checkValidity()'>Click me</button>
        </body>
    </html>

4 个答案:

答案 0 :(得分:1)

您错过了使HTML无效的结尾'

<script src='Scripts/examplefile.js></script>

function example() {
    console.log('function called');
    // blah blah blah
}
console.log('JS file was run');
<html>
    <head>
        <script src='Scripts/examplefile.js'></script>
    </head>
    <body>
        <button type='button' onClick='example()'>Click me</button>
    </body>
</html>

答案 1 :(得分:0)

尝试将您的include脚本标签放在页面底部:

/**
 * Class Response
 * @package Entity
 *
 * @ORM\Entity
 */
class Qresponse
{

    public function __construct()
    {
        $this->questions = new ArrayCollection();
    }

    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var ArrayCollection $question
     * @ORM\ManyToMany(targetEntity="Question", inversedBy="qresponses", cascade={"persist"})
     * @ORM\JoinTable(name="qresponse_question")
     */
    private $questions;

}

答案 2 :(得分:0)

我认为您可能已经在另一个函数中定义了“示例”,因此您无法在全局范围内使用它。

此代码与您提供的代码一样,效果很好:

<html>
    <head>
      <script>
        function example() {
            console.log('function called');
            // blah blah blah
        }
        console.log('JS file was run');
      </script>
    </head>
    <body>
        <button type="button" onClick="example()"">Click me</button>
    </body>
</html>

您还可以使用此笔在线进行测试:https://codepen.io/jmelfers/pen/bmRVVL?editors=1011

答案 3 :(得分:0)

晚点参加聚会,但对将来的搜索者有用。代码很好,但是我遇到了同样的问题。

进行测试时,请在源代码下(检查元素时)查看脚本是否确实存在。 否则,请进行强制刷新,直到可见为止。

相关问题