English 中文(简体)
意外的JQuery令人惊叹。。。但是它是如何工作的(方法缺少类型语法)?
原标题:Unexpected JQuery awesomeness... But how does it work (method missing type syntax)?

很抱歉标题含糊不清,我想不出一个简洁的方法来概括这个问题。我是Javascript和JQuery的新手,需要根据复选框的值对其进行切换。搜索该网站发现了很多答案,主要是以下形式:

$("input[type= checkbox ]").click(function() {
    if( $(this).is( :checked ) ) {
        //code here
    }
})

然而,在一瞬间的动态打字灵感中,我尝试在我的Javascript控制台中键入以下内容:

 $("input[type= checkbox ]").click(function() {
    if( this.checked ) {
        //code here
    }
})

……令我惊讶的是,它成功了!幕后发生了什么?是否定义了一个名为checked的方法,或者某种默认属性,甚至是缺少概念的Ruby风格的方法?这是JQuery启用的还是Javascript固有的?

它给我的印象非常棒,我想更好地理解它。

问题回答

这基本上可以归结为This$(This)之间的区别。(在此处阅读更多

this是当前对象的DOM对象,其中as$(this)为jQuery包装版本。这意味着您可以执行This.checked,这与调用普通Javascript相同。

但这意味着,正如@Val所说,你可能会遇到跨浏览器问题,因为你不依赖jQuery来为你解决这些问题。

它工作的原因是,当调用处理程序时,它会执行以下操作:

callbackfn.call(<reference to event obj>, .. params .. )

如果您查看JS引用,您将看到传递给.call的第一个参数是您希望函数在其中运行的上下文。因此,在这种情况下,由于传入的对象是单击的项目,因此它将是上下文。

我不同意其他人的回答,即这会给xss浏览器兼容性带来任何麻烦,这就是你应该做的,许多jQuery库都依赖于此。

请参阅这篇堆叠式文章

$(this)[0] == this




相关问题
selected text in iframe

How to get a selected text inside a iframe. I my page i m having a iframe which is editable true. So how can i get the selected text in that iframe.

How to fire event handlers on the link using javascript

I would like to click a link in my page using javascript. I would like to Fire event handlers on the link without navigating. How can this be done? This has to work both in firefox and Internet ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Clipboard access using Javascript - sans Flash?

Is there a reliable way to access the client machine s clipboard using Javascript? I continue to run into permissions issues when attempting to do this. How does Google Docs do this? Do they use ...

javascript debugging question

I have a large javascript which I didn t write but I need to use it and I m slowely going trough it trying to figure out what does it do and how, I m using alert to print out what it does but now I ...

Parsing date like twitter

I ve made a little forum and I want parse the date on newest posts like twitter, you know "posted 40 minutes ago ","posted 1 hour ago"... What s the best way ? Thanx.

热门标签