Javascript 如何引用正在更改的当前元素?

Javascript 如何引用正在更改的当前元素?,javascript,jquery,Javascript,Jquery,我有一个元素的onchange=,我想找到最接近的'tr'的ID 问题是,我不知道如何引用我刚刚更改的元素而不必使用唯一标识符,因为页面上可能有多个元素。我以为这是某种形式的美元——但这似乎不起作用 这是我的密码: JS: HTML: 从标记中删除onchange事件,并为jQuery选择器添加css类名。我添加了一个名为lookable的css类名 无需添加css类名并在jQuery选择器中使用它。您可以在jQuery选择器中使用name属性。但是,如果您想对多个SELECT元素执行相同的行为

我有一个元素的onchange=,我想找到最接近的'tr'的ID

问题是,我不知道如何引用我刚刚更改的元素而不必使用唯一标识符,因为页面上可能有多个元素。我以为这是某种形式的美元——但这似乎不起作用

这是我的密码:

JS:

HTML:

从标记中删除onchange事件,并为jQuery选择器添加css类名。我添加了一个名为lookable的css类名

无需添加css类名并在jQuery选择器中使用它。您可以在jQuery选择器中使用name属性。但是,如果您想对多个SELECT元素执行相同的行为,最好使用CSS类(而不是名称)对它们进行分组。我更喜欢尽可能保持元素的唯一名称。

从标记中删除onchange事件,并为jQuery选择器添加css类名。我添加了一个名为lookable的css类名

无需添加css类名并在jQuery选择器中使用它。您可以在jQuery选择器中使用name属性。但是,如果您想对多个SELECT元素执行相同的行为,最好使用CSS类(而不是名称)对它们进行分组。我希望尽可能为元素保留唯一的名称。

而不是

<select name="resolution" onchange="updateChannel();">
而不是

<select name="resolution" onchange="updateChannel();">
只需使用事件绑定。标记中的此项必须引用窗口

$(function(){

   $('[name="resolution"]').change(updateChannel)
}

function updateChannel()
{
    var channeltoupdate = $(this).closest('tr').attr('id'); // here now this will be the select element
    console.log(channeltoupdate);
}
或者用这个方法试试

拿着它

function updateChannel(elem)
{
 // here now elem will be the select element
  ...
}
只需使用事件绑定。标记中的此项必须引用窗口

$(function(){

   $('[name="resolution"]').change(updateChannel)
}

function updateChannel()
{
    var channeltoupdate = $(this).closest('tr').attr('id'); // here now this will be the select element
    console.log(channeltoupdate);
}
或者用这个方法试试

拿着它

function updateChannel(elem)
{
 // here now elem will be the select element
  ...
}

因为您没有向函数传递任何参数,所以它不知道$this是什么。尝试:

更好的方法是,去掉内联JavaScript,在document.ready调用中或在DOM中存在用于更改的元素之后添加jQuery事件处理程序:

$('select[name="resolution"]').change(function(){
   var channeltoupdate = $(this).closest('tr').attr('id');
   console.log(channeltoupdate);
});

因为您没有向函数传递任何参数,所以它不知道$this是什么。尝试:

更好的方法是,去掉内联JavaScript,在document.ready调用中或在DOM中存在用于更改的元素之后添加jQuery事件处理程序:

$('select[name="resolution"]').change(function(){
   var channeltoupdate = $(this).closest('tr').attr('id');
   console.log(channeltoupdate);
});

谢谢这很有效。我喜欢使用内联函数,然后在它正常工作后将其移动到主js中。好的。别忘了提到事件处理程序需要放在哪里,即使我们中的一些人对此很清楚,否则最好的答案是:谢谢!这很有效。我喜欢使用内联函数,然后在它正常工作后将其移动到主js中。就可以了。别忘了提到事件处理程序需要放在哪里,即使我们中的一些人对此很清楚,否则答案很好:
    <select name="resolution" onchange="updateChannel(this);">
function updateChannel(elem)
{
 // here now elem will be the select element
  ...
}
<select name="resolution" onchange="updateChannel(this);">
function updateChannel(foo){
    var channeltoupdate = $(foo).closest('tr').attr('id');
    console.log(channeltoupdate);
}
$('select[name="resolution"]').change(function(){
   var channeltoupdate = $(this).closest('tr').attr('id');
   console.log(channeltoupdate);
});