Javascript 捕获所选选项返回值未定义
我需要捕获所选的用户选项,并在post请求中发送该值 让我们忽略post部分,因为它与问题没有直接关系 但现在该值显示为未定义 CodePen:Javascript 捕获所选选项返回值未定义,javascript,jquery,html,Javascript,Jquery,Html,我需要捕获所选的用户选项,并在post请求中发送该值 让我们忽略post部分,因为它与问题没有直接关系 但现在该值显示为未定义 CodePen: <script> $("#agregarProducto1").click(function () { var lista_id; $('#listas-de-usuario').change(function() { var lista_id = $(this).find('option:select
<script>
$("#agregarProducto1").click(function () {
var lista_id;
$('#listas-de-usuario').change(function() {
var lista_id = $(this).find('option:selected').val();
});
alert(lista_id);
// $.post("{% url 'listas/agregar-producto/", {
// c_slug: "cuadernos",
// s_slug: "Cuadernos",
// product_slug: "cuadernos-rojos",
// lista_id: lista_id,
// });
});
</script>
我有这个JS,但是我需要捕获的值lista\u id
,显示为未定义的。为什么?
我尝试将其设置为全局变量。在JS中,您将看到
警报,此警报针对lista\u id
JS:
<script>
$("#agregarProducto1").click(function () {
var lista_id;
$('#listas-de-usuario').change(function() {
var lista_id = $(this).find('option:selected').val();
});
alert(lista_id);
// $.post("{% url 'listas/agregar-producto/", {
// c_slug: "cuadernos",
// s_slug: "Cuadernos",
// product_slug: "cuadernos-rojos",
// lista_id: lista_id,
// });
});
</script>
$(“#agregarProducto1”)。单击(函数(){
var lista_id;
$('#listas de usuario')。更改(函数(){
var lista_id=$(this).find('option:selected').val();
});
警报(列表id);
//$.post(“{%url”列表/agregar producto/”{
//c_鼻涕虫:“cuadernos”,
//s_鼻涕虫:“Cuadernos”,
//产品名称:“cuadernos rojos”,
//lista_id:lista_id,
// });
});
您可以在全局或周围函数中只声明一次变量,然后不在单击或更改
处理程序中声明它们。这样,它就是您引用的同一个变量
另外,要绑定change
处理程序的代码可能在click
处理程序之外,否则每次单击按钮时都会绑定它
全局变量声明示例:
jQuery的文档就绪
函数中声明的变量示例: