附加后Jquery选择正确

时间:2016-01-22 08:24:02

标签: javascript jquery html ajax

我的页面中有一个按钮,点击它后,它会附加一些带有 .select2-selection__rendered 类的元素。所以我想在追加之后得到它的文本,并且当页面加载时它不会附加,当我点击一个按钮时它会附加,之后我想在AJAX调用中使用它,但是当我通过警告它来测试它时#39; s文本我什么都没有,它是空白的! 。附加没有问题。它附加了 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);
          });
      });  

============================== NEW EDITED =============== ============

嘿伙计们,我不想附加某些内容,我想选择脚本附加的元素文本,该脚本仅在我点击myButtn(名称为例)时才会运行。 那个剧本不是我写的,而且时间太长了,我下载了...等等让我给你看一个例子

See the Above image....Now see this below image

参见上面的图片....现在看下面的图像

enter image description here

现在有任何建议或帮助......? :(

============================== EDITED ================ =================

2 个答案:

答案 0 :(得分: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);
  });
});

答案 1 :(得分:0)

<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>