jquery获取动态添加的表单元素

发布于 2022-09-01 23:18:02 字数 393 浏览 20 评论 0

有一个页面,在页面载入的时候,使用ajax动态创建一个input元素,如下

success: function(file, response){
      response = JSON.parse(response);
      img_path = response.file_path;
      html = '<input type="hidden" class="goods_other_img" name="goods_other_img[]" value="'+img_path+'" />';
      $('#goods_other_img').append(html);
    }

jquery选择器不能选择动态添加的元素,请问该如何获得新添加的这个input?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

歌枕肩 2022-09-08 23:18:02
var input = $('#goods_other_img').children('.goods_other_img');
情魔剑神 2022-09-08 23:18:02

对于创建的元素,想要获取它,可以用on,详情百度之。

苦行僧 2022-09-08 23:18:02

按照正常的代码执行顺序

html = '<input type="hidden" class="goods_other_img" name="goods_other_img[]" value="'+img_path+'" />';
$('#goods_other_img').append(html);
console.log($('.goods_other_img').val());

是可以执行的,也就是获取之前要确保已经将元素添加到document中。

你这个是异步执行的,应该把获取元素的代码写在回调函数里面。

$.ajax({
    type : 'get',
    url : '',
    success: function(file, response){
        response = JSON.parse(response);
        img_path = response.file_path;
        html = '<input type="hidden" class="goods_other_img" name="goods_other_img[]" value="'+img_path+'" />';
        $('#goods_other_img').append(html);
        console.log($('.goods_other_img').val()); //可以获取到
    }
});
console.log($('.goods_other_img').val()); //可能获取不到
绝不放开 2022-09-08 23:18:02

试试给input元素加上id再用选择器获取

与往事干杯 2022-09-08 23:18:02

可以啊,
$('#goods_other_img').append(html);
DOM树中已经添加好了
就可以选择啦
$('#goods_other_img input.goods_other_mg')

许你一世情深 2022-09-08 23:18:02

这个你要在ajax请求完的回调里面去获取dom

你想一下,你页面加载的时候,你数据还没有渲染进去,选择器就去选择了肯定是拿不到的

$.ajax({
    url: '',
    type: 'default GET (Other values: POST)',
    dataType: 'default: Intelligent Guess (Other values: xml, json, script, or html)',
    data: {param1: 'value1'},
    success: function(data){
        if(data.msg == 1){ //请求成功
            $(ele) //可以选择
        }
    }
})
雨夜星沙 2022-09-08 23:18:02

首先不知道你是如何获取的,如果你是在ajax未执行后就去获取肯定是得不到的并且对于新增的元素要绑定事件需要用到on

$(document).on('click','. goods_other_img',function(){});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文