[英]Get text value from a button s created dynamically jquery
因此,我根据从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>
Show.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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.