Javascript使用$表示法和关键字"this"用法

Cod*_*ess 0 javascript this

我正在研究别人的javascript代码,并且我运行了一些我以前从未见过的东西.如果有人可以为我阐明它,我将非常感激.我过去使用过javascript,但我绝不是专家.

1)使用美元符号($)表示法从javascript中访问某些控件,就像JQuery一样.我有点困惑,因为脚本语言明确指定为javascript,而不是JQuery,并且项目中没有JQuery库.我想知道这是否是一种常见做法?

<script type="text/javascript">
function select1_onchange()
{
    $('Button1').style.display = (this.value == "No" ? 'block' : 'none');
    $('OptionsBox').style.display = (this.value == "Yes" ? 'block' : 'none');
}
</script>
Run Code Online (Sandbox Code Playgroud)

2)第二件事是在上面的代码中,关键字this似乎是指调用脚本的对象,同时在当前上下文中javascript解释thiswindow对象.这使得此代码无效.我应该在这种特殊情况下this.value$('Button1').value或替换document.getElementById('Button1')(或document.getElementsByName('Button1')[0],因为开发人员使用了name属性而不是id)?哪一个会更有效率?或者另一种选择 - 我应该将关键字传递this给函数然后this用输入变量替换吗?

<script type="text/javascript">
function select1_onchange(mySelect)
{
    $('Button1').style.display = (mySelect.value == "No" ? 'block' : 'none');
    $('OptionsBox').style.display = (mySelect.value == "Yes" ? 'block' : 'none');
}
</script>
Run Code Online (Sandbox Code Playgroud)

并称之为:

<select name="select1" onchange="select1_onchange(this)">
<option selected value="">Select</option>
<option value="Yes">Yes</option>
<option value="No">No</option>
</select>
Run Code Online (Sandbox Code Playgroud)

选择这两种方法有什么优点和缺点?

ade*_*neo 8

有人可能创造了自己的小功能,如

var $ = function(id) {
    return document.getElementById(id);
}

$('Button1').style.display = 'none';
Run Code Online (Sandbox Code Playgroud)

在简单的javascript中,jQuery的编写方式有点相同,因为它只是一个方便的"辅助函数"库 .
要检查jQuery是否存在,可以做typeof jQuery,应该返回"function"

附加内联事件处理程序时,可以传递参数

<select name="select1" onchange="select1_onchange('hello kitty')">
  <option>1</option>
  <option>2</option>
</select>

<script>
    function select1_onchange(something) {
        alert(something); // "hello kitty"
    }
</script>
Run Code Online (Sandbox Code Playgroud)

传递this而不是字符串,给出一个元素的引用,在大多数情况下它将是window,所以它不是真正的通常做的事情

<select name="select1" onchange="select1_onchange(this)">
  <option>1</option>
  <option>2</option>
</select>

<script>
    function select1_onchange(something) {
        alert(this); // [object Window]
    }
</script>
Run Code Online (Sandbox Code Playgroud)

这些天,应该使用addEventListener,它会自动将this回调内的值设置为绑定元素.

<select name="select1" id="select1">
  <option>1</option>
  <option>2</option>
</select>

<script>
  
  document.getElementById('select1').addEventListener('change', function() {
    alert(this.id); // "select1"
  }, false);
</script>
Run Code Online (Sandbox Code Playgroud)

  • @NodeNodeNode - 如果在控制台中运行,那是真的,大多数浏览器都有自己的`$`函数.但是,这是用.html文件中的脚本标记编写的代码,并且dev-tools中的`$`在该范围内不可用.至于'this`指的是什么,附上一个片段,你可以自由尝试. (2认同)