如何使用Jquery获取clicked div中输入标记的值?

时间:2016-03-18 08:06:44

标签: javascript php jquery html ajax

我有一个以下的Ajax成功函数,当用户加载页面或添加文件夹时,它会在DOM中打印文件夹div。

for(var i in output.dirs){
        //console.log(output.dirs[i]);
        var html = '<div class="col-sm-3 text-center" id="img-folder"><input type="hidden" id="folder-names" name="open-folder" value="'+output.dirs[i].name+'"/>';
            html+='<div class="mid-folder">  <i class="fa fa-folder fa-5x"></i>';
            html+='<h3 class="title-folder">'+output.dirs[i].name.substr(0,15)+".."+'</h3></div>';
            $(".folders").append(html);

我想在单击每个文件夹时添加另一个Ajax请求。我想发送被单击的文件夹的文件夹名称,并通过Ajax将其发送到PHP控制器,以便我可以检索该文件夹中的图像。为此,我附加了一个带隐藏属性的输入标签,将文件夹名称打印为值,这样我就可以很容易地使用.val()来获取值。

但问题在于我怎么知道哪个文件夹被点击了,以及属于该div的<input>标签的值是多少,因为每个打印的div都有相同的id“img-folder” 。

看一些替代方案,我发现了这个:

$("#img-folder").each(function(i){
$(this).on("click",function(){
   // Now how would I select the <input> tag value here, so that I could    pass the value into the controller? 
});
});

我现在要做的是捕获被点击的文件夹的值/文件夹名称,并将值发送到我的ajax函数,如下所示:

// function for showing the images and contents inside the folders. 
  $(function(){
    $(document.body).on('click',"#img-folder",function(e){
     console.log($("#folder-names").val());
      //e.preventDefault();
      $.ajax({
        url:'<?php echo base_url("Welcome/show_image"); ?>',
        type:'POST',
        data:$('#folder-name').val(),
        success:function(data){
          console.log(data);

        },
      });
    })
  })

解决此问题的任何建议或任何其他逻辑?这会很棒。

2 个答案:

答案 0 :(得分:2)

您正在复制元素的ID。 ID必须是唯一的。你可以宁愿给同一个班级。像这样:

for(var i in output.dirs){
    //console.log(output.dirs[i]);
    var html = '<div class="col-sm-3 text-center" class="img-folder"><input type="hidden" class="folder-names" name="open-folder" value="'+output.dirs[i].name+'"/>';
        html+='<div class="mid-folder">  <i class="fa fa-folder fa-5x"></i>';
        html+='<h3 class="title-folder">'+output.dirs[i].name.substr(0,15)+".."+'</h3></div>';
        $(".folders").append(html);

然后使用类选择器在单击的folder-names中找到包含类img-folder的元素:

 $(function(){
$(document.body).on('click',".img-folder",function(e){
 var folderval = $(this).find(".folder-names").val();
 console.log($(this).find(".folder-names").val());
  //e.preventDefault();
  $.ajax({
    url:'<?php echo base_url("Welcome/show_image"); ?>',
    type:'POST',
    data:folderval ,
    success:function(data){
      console.log(data);

    },
  });
 });
});

答案 1 :(得分:1)

这就是你所需要的 -

使用jQuery this,您将获得该元素的属性值。因此,在您的情况下,它是input。您将存储该属性值并将其传递给AJAX调用。

$(this).on("click",function(){
   var inputValue = $(this).attr('value');
        $.ajax({
    url:'<?php echo base_url("Welcome/show_image"); ?>',
    type:'POST',
    data: inputValue ,
    success:function(data){
      console.log(data);

    },
  });
});
相关问题