我如何在函数中使jquery id选择等于这个

How do I make a jquery id selection equal to this inside a function?

本文关键字:id jquery 选择 于这个 函数      更新时间:2023-09-26

为什么我得到一个错误,当我试图使$("#select-province") that.value ?

function updateCities(that){
   console.log(that.value);
}
$(document).ready(function(){
      updateCities($("#select-province"));
});

您需要将jquery对象转换为javascript object.use:

function updateCities(that){
  console.log(that.value);
}
$(document).ready(function(){
  updateCities($("#select-province")[0]);
});

选择1,但不能两者都选:

  • 传递一个DOM对象,而不是jQuery对象

    function updateCities(that){
        console.log(that.value);
    }
    $(document).ready(function(){
        updateCities(document.getElementById('select-province'));
    });
    
  • 因为你正在传递一个jQuery对象,使用库的函数来正确检索值:

    function updateCities($that){
        console.log($that.val());  // or $that.prop('value')
    }
    $(document).ready(function(){
        updateCities($("#select-province"));
    });
    

    注意,我将that的名称改为$that,以反映它是一个jQuery对象

在使用jQuery时,要尽可能地使用jQuery

function updateCities(that){
  console.log($(that).val());
}
$(document).ready(function(){
  updateCities($("#select-province"));
});

使用jquery $(that).val()效果良好

function updateCities(that){
  console.log($(that).val());
}
$(document).ready(function(){
      updateCities($("#select-province"));
});

参见提琴链接http://jsfiddle.net/5AX6p/1/