在JavaScript中传递'this'作为参数

时间:2012-01-31 19:10:11

标签: javascript jquery

我有以下代码:

HTML:

<label id="copyAddress" class="copyAddress" onclick="CopyAddress(this);">
    Copy Address
</label>

JS:

function CopyAddress(copyAddressLink) {    
  PopulateTarget(copyAddressLink);   
}

function PopulateTarget(link) {
  var targetGroup = $(link).closest('someClass');    
}

在PopulateTarget函数中,'link'变量是未定义的,而在CopyAddress中它具有应该的值。

什么可能导致这个问题?在Java Script中传递参数有一些限制吗?这应该如何表现?如果您需要更多代码发布,请告诉我。

3 个答案:

答案 0 :(得分:2)

你在“someClass”上错过了一个点,它应该是“.someClass”。

也许你的代码在修复后会起作用。但是:既然你正在使用jQuery(看起来你是),你应该用jQuery方式附加click处理程序,而不是在HTML上内联。这意味着:

$(document).ready(function(){
    $('#copyAddress').click(CopyAddress);
})

function CopyAddress() {    
    PopulateTarget(this);   
}

function PopulateTarget(link) {
    var targetGroup = $(link).closest('someClass');    
}

答案 1 :(得分:1)

您不应混淆HTML和JS。您应该在JS代码中以编程方式附加JS处理程序:

<!-- note: no onclick in this html -->
<label id="copyAddress" class="copyAddress">Copy Address</label>
// Wait until the page is loaded before starting to look for elements
$(function(){

  // Assuming jQuery 1.7
  $('#copyAddress').on('click',copyAddress);

  // …alternatively, for older jQuery
  $('#copyAddress').click(copyAddress);

  function copyAddress(evt){
    // The 'target' property of the event object passed in is the object
    // upon which the event was first triggered.
    PopulateTarget(evt.target);
  }
});

在上述情况下,您可以使用this而不是evt.target,因为您直接将事件绑定在该对象上。但是,如果页面上有各种执行此功能的项目,则会变得更加强大。您可以将事件处理程序附加到某个父对象,然后在回调期间询问 - 单击了哪个元素。那看起来像是:

// Watch for any element with a copyAddress class to be clicked on,
// even if they are added after this code has run
$(document.body).on('click','.copyAddress',function(evt){
  var target = evt.target;
  console.log("You clicked on",target);
});

答案 2 :(得分:0)

因为你似乎在使用jQuery:

您可以使用jQuery.proxythis绑定到特定值。它的使用方式如下:

jQuery.proxy(function () { console.log(this); }, this);