简体   繁体   English

无法使用onclick事件调用JavaScript函数

[英]Not able to call a javascript function using onclick event

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <title>Getting Started With PubNub</title>
  </head>
  <body>

    HotelName: <input type="text" id="rname"/> <br/>
    <input type = "button" value = "Submit" onclick = "publish()"/>

    <script src="https://cdn.pubnub.com/pubnub.min.js"></script>
    <script charset="utf-8">
      (function(){

        var PUBNUB_demo = PUBNUB.init({
          publish_key: 'demo',
          subscribe_key: 'demo'
        });

        PUBNUB_demo.subscribe({
          channel: 'b',
          message: function(m){console.log(m)},
          connect : publish
        });

        function publish() {
          var hn = document.getElementById('rname').value
          var hname = JSON.stringify(hn);
          PUBNUB_demo.publish({
            channel: 'a',
            message: {"text":hn}
          });
        }

      })();

    </script>

  </body>
</html>

In this the onclick='publish()' is not getting executed. 在这种情况下,不会执行onclick='publish()' The error shown is Uncaught ReferenceError: publish is not defined . 显示的错误是Uncaught ReferenceError: publish is not defined Although I have already defined the publish function. 尽管我已经定义了发布功能。 The publish function should get the value of the text box and add it the JSON that I am sending to the publish function. 发布功能应获取文本框的值,并将其添加到我要发送到发布功能的JSON中。

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <title>Getting Started With PubNub</title>
  </head>
  <body>
    <script src="https://cdn.pubnub.com/pubnub.min.js"></script>
    <script charset="utf-8">


        var PUBNUB_demo = PUBNUB.init({
          publish_key: 'demo',
          subscribe_key: 'demo'
        });

        PUBNUB_demo.subscribe({
          channel: 'b',
          message: function(m){console.log(m)},
          connect : publish
        });

        function publish(hn) {
          hnaam = JSON.stringify(hn);
          PUBNUB_demo.publish({
            channel: 'a',
            message: {"text":hnaam}
          });

        }

        function getName(){
          var hname= document.getElementById("rname").value;
          document.getElementById("printname").innerHTML = hname;
          publish(hname);
        }



    </script>
    <br/>
    <span id ='printname'></span>
    <br/>
    <input type ="text" id="rname"/><br>
    <input type ="button" value="Submit" onclick="getName()"/>



  </body>
</html>

Your publish() function is not working because it is not available in the global context as you're attempting to access it. 您的publish()函数不起作用,因为在您尝试访问它时,它在全局上下文中不可用。 Because your named functions are defined within a self-invoked function, they are also destroyed by the time your runtime is finished. 因为您的命名函数是在自调用函数中定义的,所以它们在运行时结束时也会被销毁。 By the time you click your button, your code has finished running and the context of your self-invoked function is no longer accessible. 当您单击按钮时,您的代码已完成运行,并且不再可以访问自调用函数的上下文。

It looks like the reason you're using an IIFE is because you don't want to pollute the global context, and while your motivations are right, you are not properly exposing your functions to the DOM. 使用IIFE的原因似乎是因为您不想污染全局上下文,并且尽管动机正确,但您没有将函数正确地暴露给DOM。

The Quick Solution 快速解决方案

You could simply remove your code from inside your self-invoked function: 您可以简单地从自调用函数内部删除代码:

    var PUBNUB_demo = PUBNUB.init({
      publish_key: 'demo',
      subscribe_key: 'demo'
    });

    PUBNUB_demo.subscribe({
      channel: 'b',
      message: function(m){console.log(m)},
      connect : publish
    });

    function publish() {
      var hn = document.getElementById('rname').value
      var hname = JSON.stringify(hn);
      PUBNUB_demo.publish({
        channel: 'a',
        message: {"text":hn}
      });
    }

The Modular Approach 模块化方法

You'll want to write modular code. 您将要编写模块化代码。 There are many different methods to do this, but the quickest and most vanilla way is called the Revealing Module Pattern. 有许多不同的方法可以执行此操作,但是最快,最有效的方法称为“显示模块模式”。

Because we don't want to pollute the global namespace, but still need to access our code, we'll create global variables called Modules, and we'll choose which functions get exposed 因为我们不想污染全局名称空间,但是仍然需要访问我们的代码,所以我们将创建称为模块的全局变量,并选择公开哪些函数。

  var MyModule = (function(){

    var PUBNUB_demo = PUBNUB.init({
      publish_key: 'demo',
      subscribe_key: 'demo'
    });

    PUBNUB_demo.subscribe({
      channel: 'b',
      message: function(m){console.log(m)},
      connect : publish
    });

    function publish() {
      var hn = document.getElementById('rname').value
      var hname = JSON.stringify(hn);
      PUBNUB_demo.publish({
        channel: 'a',
        message: {"text":hn}
      });
    }

    return {
      publish: publish()
    }

  })();

Now, in your HTML you should be able to call the following function inside your onclick attribute: 现在,在您的HTML中,您应该能够在onclick属性内调用以下函数:

MyModule.publish()

The problem is that you have your functions in ()... just get out those functions and the problem is out. 问题是您的函数在()中...只需取出这些函数即可解决问题。

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <script src="https://cdn.pubnub.com/pubnub.min.js"></script>
    <title>Getting Started With PubNub</title>
  </head>
  <body>
    HotelName: <input type="text" id="rname"/> <br/>
    <input type = "button" value = "Submit" onclick = "publish()"/>    
    <script charset="utf-8">
        var PUBNUB_demo = PUBNUB.init({
          publish_key: 'demo',
          subscribe_key: 'demo'
        });

        PUBNUB_demo.subscribe({
          channel: 'b',
          message: function(m){console.log(m)},
          connect : publish
        });

        function publish() {
          var hn = document.getElementById('rname').value
          var hname = JSON.stringify(hn);
          PUBNUB_demo.publish({
            channel: 'a',
            message: {"text":hn}
          });
        }
    </script>
  </body>
</html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM