获取动态创建的输入的值

时间:2018-12-16 16:06:04

标签: jquery pug

这是根据数据库中的信息自动生成的代码

               each p in posts              
                .w3-container.w3-card.w3-black.w3-round.w3-margin
                    p= p.title
                    input(type='hidden', id="idPost" value=p._id)
                    if p.picture
                        img.w3-margin-bottom(src="images/"+p.picture style="width:100%")
                    p= p.content
                    .w3-container.w3-card(id="commentSection") 
                        if p.comments
                            each m in p.comments
                                p= m.user.split(":")[1] + "        "+ m.message
                    textarea(id="NewComment", cols="80%", rows="1" placeholder="Enter a new comment")

我正在尝试获取输入idPost的值,但到目前为止还不算幸运。我尝试了类似$('[id=idPost]').eq(2).val()的方法,但是在这种情况下,我需要知道以前的索引,但我不知道。

我也尝试了类似的方法,我认为它是我想要的,但是我无法使其工作

var num = $(this).closest('w3-container').find(".idPost").val();

此人正在搜索类,而不是上面的代码中显示的id,但这些都不起作用

2 个答案:

答案 0 :(得分:0)

input(type ='hidden',id =“ idPost” value = p._id)

idPost是输入ID,因此您需要查找#idPost

var num = $(this).parents('。w3-container')。find(“#idPost”)。val();

答案 1 :(得分:0)

因为这两个解决方案都不可行,所以我尝试了一些方法,并且奏效了

pug

each p in posts              
            .w3-container.w3-card.w3-black.w3-round.w3-margin
                p= p.title 
                if p.picture
                    img.w3-margin-bottom(src="images/"+p.picture style="width:100%")
                p= p.content
                .w3-container.w3-card(class="commentSection" name=p._id) 
                    if p.comments
                        each m in p.comments
                            p= m.user.split(":")[1] + "        "+ m.message
                textarea(id="NewComment", cols="80%", rows="1" placeholder="Enter a new comment")

现在在我的jquery中,我只获取按“ enter”的当前textarea,然后将所有带有“ conjectSection”类的“容器”循环,并检查当前textarea的属性名称是否与commentSection的正确名称匹配。如果为true,则即时消息位于正确的位置并可以进行其余操作。

$(document).on('keydown', function(e) {
    var targetInput = $(e.target);
      if(targetInput.is('textarea')) { 
         if(e.which == 13){ 
           e.preventDefault();
           $('.commentSection').each(function() {
               if($(this).attr("name")==targetInput.attr('name')){
                $(this).append('<p>'+targetInput.val()+'</p>');
               }
            }); 
          // $("#commentSection").append('<p>'+targetInput.val()+'</p>');
           ajaxPost(targetInput.val(),targetInput.attr('name'),
           p=> alert(JSON.stringify(p)),
           e =>{
               alert('AJAX ERROR:'+JSON.stringify(e));
               console.log("AJAX ERROR:"+JSON.stringify(e));
           });
           targetInput.val('');
      }
       }
   });  

有点草率,但有效

相关问题