【问题标题】:JQuery and accessing nested input element's value of a blog postJQuery 和访问博客文章的嵌套输入元素的值
【发布时间】:2016-03-05 14:27:54
【问题描述】:

我正在开发自己的博客,类似于某种 facebook 克隆。我需要使删除一些帖子成为可能,而我打算做的是在每个帖子中插入一个带有帖子 ID 的隐藏(尚未隐藏)输入。所以我对每个帖子都有一个大字符串,如下所示:

    $('#blog').append('<div class="blogPost"><div class="postTitre">' +title + '</div>' + 
                          '<div class="postDescription">' + description + '</div>' + 
                          '<div class="postTimeStamp">' + timestamp + '</div>' + 
                          '<embed class="embedPDF" src="./uploads/' + name + '#toolbar=0&navpanes=0&scrollbar=0"/>' + 
                          '<div class="closeDelete">
                              <input type="text" name="txtID" readonly="readonly" value="' + id + '" />X
                              <div class="close-text">DELETE</div>' +
                          '</div>
                       </div>');

我需要访问名为 txtID 的内部输入类型,该类型将被隐藏。

我尝试了很多东西来让它发挥作用,但没有一个能达到我想要的效果。现在,我有这个使用事件委托的代码,但不确定如何获取我的文本输入的值:

            //THIS WILL FIRE THE DELETE POST EVENT
            $("#blog").on("click", "div.closeDelete", function(){
                var id = $("div.closeDelete").find("input[name=txtID]").val();
                alert("close delete this: " + id + " post");
            });

【问题讨论】:

  • 有什么问题?
  • You're close...this 将成为被点击的div.closeDelete ;)
  • 我生成各种 blogPost 分类的 div 并在其中生成 div.closeDelete 并在输入中生成 ID。需要恢复输入的值。

标签: jquery blogs


【解决方案1】:

this 将是被点击的div.closeDelete
用它来查找对应的id就行了

var id = $(this).find('input[name="txtID"]').val();  // instead of $("div.closeDelete").find(...)

$("#blog").on("click", "div.closeDelete", function() {
  var id = $(this).find('input[name="txtID"]').val();
  console.log("close delete this: " + id + " post");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="blog">
  <div class="blogPost">
    <div class="postTitre">title</div>
    <div class="closeDelete">
      <input type="text" name="txtID" readonly="readonly" value="123" />X
      <div class="close-text">DELETE</div>
    </div>
  </div>
  <div class="blogPost">
    <div class="postTitre">title</div>
    <div class="closeDelete">
      <input type="text" name="txtID" readonly="readonly" value="342" />X
      <div class="close-text">DELETE</div>
    </div>
  </div>
  <div class="blogPost">
    <div class="postTitre">title</div>
    <div class="closeDelete">
      <input type="text" name="txtID" readonly="readonly" value="486" />X
      <div class="close-text">DELETE</div>
    </div>
  </div>
</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-12-25
    • 2011-07-11
    • 1970-01-01
    • 2015-05-19
    • 1970-01-01
    • 2021-07-09
    • 2010-12-02
    • 1970-01-01
    相关资源
    最近更新 更多