从动态创建的按钮中获取文本值 jquery

Get text value from a button s created dynamically jquery

本文关键字:获取 取文本 jquery 按钮 动态 创建      更新时间:2023-09-26

所以我根据从我的 generateFolderTree 函数返回的数组值动态地将按钮添加到表中,问题是我似乎无法获取单击按钮的文本值,甚至无法在单击创建的按钮时获取任何事件。如何获取点击按钮的名称?下面的代码....谢谢

Jquery

   <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(function(){
$("#selectFolder").click(runMyFunction);
});
function runMyFunction(){
google.script.run
.withSuccessHandler(successCallback)
.withFailureHandler(showError)
.generateFolderTree();
 $("#hiddenAttrib").hide();
}
function showError(error) {
    console.log(error);
    window.alert('An error has occurred, please try again.');
  }
  function successCallback(returnedArray)
  {
    console.log("returnedArray" + returnedArray);
    var folders = returnedArray;
   console.log("folders" + folders);
    var i = 0;
    //row;
    for( i=0; i<folders.length;i++)
    {
       console.log("i = " + i);
   var row = $('<p><tr><button class = "selectedFolder">' + folders[i] + '</button></tr></p>');
    $("#source").append(row.html());
    }
  }
 $(".selectedFolder").click(function () {
var text = $(this).text();
console.log(text);
$("#dialog-status").val(text);
}); 

</script>

显示.html

   <!-- USe a templated HTML printing scriphlet to import common stylesheet. -->
<?!= HtmlService.createHtmlOutputFromFile("Stylesheet").getContent(); ?>
<!-- Use a templated HTML printing scriptlet to import JavaScript. -->
<div>
<div class = "block" id = "dialog-elements">
<button class = "selectFolder" id = "selectFolder" >Select a Folder</button>
</div>
<!-- This block is going to be hidden until the user selects a folder -->
<div class = "block" id = "hiddenAttrib">
<p><label for = "SelectedFolder"> Selected Folder: </label></p>
<p><label id = "foldername"> Folder Name: </label></p>
<p><label id = "folderid"> Folder ID: </label></p>
</div>
<div class = "folderTable" id = "folderTable">
<p><label class = "showStatus" id = "dialog-status">Selected Folder: </label></p>
<table style = "width:100%" id = "source">
</table>

</div>
</div>
<!-- Use a templated HTML printing scriptlet to import JavaScript. -->
<?!= HtmlService.createHtmlOutputFromFile('ShowJavaScript').getContent(); ?>
 $('document').on('click', '.selectedFolder', function () {
            alert($(this).text())
        });

把你的这段代码放在 $(document).ready 中

$(".selectedFolder").click(function () {
var text = $(this).text();
console.log(text);
$("#dialog-status").val(text);
}); 

使用

$(ELEMENT/CLASS/ID).on('click', function(){});

而不是

$(ELEMENT/CLASS/ID).click

在我们习惯使用 live() 为动态创建的元素附加事件之前,click()函数不会考虑动态添加到 DOM 的元素,但由于live()已贬值,我们应该使用 on()

on()充当live()