【问题标题】:Jquery Selecting Right After appending追加后立即选择Jquery
【发布时间】:2016-01-22 08:24:01
【问题描述】:

我的页面中有一个按钮,单击它后,它会附加一些带有 .select2-selection__rendered 类的元素。所以我想在附加后获取它的文本,它不会在页面加载时附加,它会在我单击按钮时附加,然后我想在 AJAX 调用中使用它,但是当我通过提醒它的文本来测试它时我什么都没有,它是空白的! .追加没有问题。它附加了它的 span 元素。 这是我选择文本的脚本。

$(document).ready(function(){  
          function () {
        var postTitle = $(".select2-selection__rendered").text(); //selecting text
        $("div#sdf").click(function(){ //this div is like a button
              alert("Title is: " + postTitle);
          });
      });  

===============================新编辑=============== =============

嘿伙计们,我不想附加一些东西,我想选择脚本附加的元素文本,并且该脚本仅在我单击 myButtn(名称作为示例)时运行。 而且那个脚本不是我写的,太长了,我下载了……等我给你看个例子

见上图....现在看下图

现在有什么建议或帮助....? :(

===============================已编辑================ =================

【问题讨论】:

  • 提供样本作品!提供失败的场景..
  • append 的代码在哪里?
  • extra function () { 只是问题错字,对吧?!我想你应该在点击处理程序中设置var postTitle = $(".select2-selection__rendered").text();
  • 请提供您的 html 代码...

标签: javascript jquery html ajax


【解决方案1】:

如果我理解正确,你的意思是这样的:

$(document).ready(function(){  
  $("div#sdf").click(function(){
    var select2 = $(".select2-selection__rendered").appendTo('body'); // replace 'body' by the DOM element to append to
    var postTitle = select2.text();
    alert("Title is: " + postTitle);
  });
});

甚至

$(document).ready(function(){  
  $("div#sdf").click(function(){
    var postTitle = $(".select2-selection__rendered").appendTo('body').text(); // replace 'body' by the DOM element to append to
    alert("Title is: " + postTitle);
  });
});

根据编辑的评论,我认为这应该可行:

$(document).ready(function(){  
  $("div#sdf").click(function(){
    var postTitle = $(".select2-selection__rendered").text();
    alert("Title is: " + postTitle);
  });
});

【讨论】:

  • 谢谢,但这不是我想要的,你能检查一下编辑过的文字吗?希望你能帮忙。
  • 我进行了更改。我认为您的代码中的主要错误是$(".select2-selection__rendered").text() 的位置。如果您在页面加载时执行此操作,则外部脚本尚未附加该元素。然后,如果您改为单击(当内容存在时),那应该可以工作。请告诉我。谢谢
【解决方案2】:
<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>

<script>

    $(document).ready(function(){  

            var postTitle = $(".select2-selection__rendered").text(); //selecting text
            $("div#sdf").click(function () { //this div is like a button
                $(".select2-selection__rendered").append("<span style='color:red;'>hello</span>")
            });
        });  
</script>
</head>
<body>
   <div class="select2-selection__rendered" >
        sample Text
    </div>
    <br />
    <div id="sdf">Click Me</div>
</body>
</html>

【讨论】:

  • 谢谢,但这不是我想要的,你能检查一下编辑过的文字吗?希望你能帮忙。
猜你喜欢
  • 2012-08-08
  • 2022-01-17
  • 2018-02-21
  • 2016-03-18
  • 2014-01-05
  • 2018-09-11
  • 2014-07-08
  • 1970-01-01
  • 2011-06-25
相关资源
最近更新 更多