【问题标题】:JQuery Terminal term.echo from another function?JQuery Terminal term.echo 来自另一个函数?
【发布时间】:2013-03-30 05:51:49
【问题描述】:

我正在尝试使用:http://terminal.jcubic.pl/

我希望能够从另一个函数调用 term.echo 以便能够在终端内放置数据,但我无法引用它。

代码如下:

jQuery(document).ready(function($) {
    var id = 1;
    $('body').terminal(function(command, term) {
        if (command == 'help') {
            term.echo("available commands are mysql, js, test");
        } else{
          term.echo("entered: " + command);
        }

    }, {
        greetings: "Shell",
        onBlur: function() {
            return false;
        }
    });
});

如何从外部访问term.echo,这样我就可以像一个按钮一样点击调用term.echo来添加数据?

【问题讨论】:

    标签: javascript jquery jquery-terminal


    【解决方案1】:

    最简单的方法是使用全局变量作为 term 对象的引用。在您的示例中,可能如下所示:

    // global placeholder for term object
    var terminal = null;
    
    jQuery(document).ready(function($) {
        var id = 1;
        $('body').terminal(function(command, term) {
    
            // setting up global reference
            terminal = term;
    
            if (command == 'help') {
                term.echo("available commands are mysql, js, test");
            } else{
              term.echo("entered: " + command);
            }
    
        }, {
            greetings: "Shell",
            onBlur: function() {
                return false;
            }
        });
    });
    

    此代码的问题是它会在 document 上触发 ready 事件后加载终端,而您永远无法确定何时会发生这种情况。

    在 document.ready 被触发后,您将能够在任何地方使用terminal.echo('');

    【讨论】:

      【解决方案2】:

      终端返回的值与interpter参数中的对象是同一个对象(在这两种情况下都是带有附加终端方法的jQuery对象),所以你可以这样做:

      jQuery(function($) {
          var terminal = $('body').terminal(function(command, term) {
              if (command == 'help') {
                  term.echo("available commands are mysql, js, test");
              } else{
                term.echo("entered: " + command);
              }
      
          }, {
              greetings: "Shell",
              onBlur: function() {
                  return false;
              }
          });
      
          terminal.echo("Some text");
      });
      

      【讨论】:

      • 我可以只发送带有 echo() 的字符吗?它在我的文本之后附加了一个新行。我不想要那个!
      • @0xFEEDC0DE 你不能,echo 总是会在末尾添加新行。
      • 我不想在每次回显后添加新行。是否有其他功能可以做到这一点?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-02-16
      • 2017-03-08
      • 1970-01-01
      • 2021-08-05
      • 2012-03-13
      • 2020-08-11
      • 1970-01-01
      相关资源
      最近更新 更多