我正在动态添加<script>
每当按下按钮时,我都会将带有 javascript 和 jQuery 的标签添加到我的 html 文件中。所有内容都已正确添加,但只有两者之一 .click
jQuery 操作函数正在运行。我似乎不明白为什么。控制台中没有错误。我确定我使用了 \'
和\"
在正确的地方。
$('#classBox').append('<tr id=\"' + tempCHAR + tempNUM + '\">'
+ '<td>'
+ '<i id=\"' + tempCHAR + tempNUM + '\" class=\"icon-remove-sign\">'
+ '</i> '
+ '<a id=\"' + tempCHAR + tempNUM + '\"" href=\"https://cms.psu.edu/section/default.asp?id=' + urlHOLDER + '\" target="framehidden">'
+ tempYEAR + ': ' + tempCHAR + tempNUM + ', Section ' + tempSEC
+ '</a>'
+ '</td>'
+ '</tr>'
+ '<script>'
+ '$(\'#' + tempCHAR + tempNUM + '\').click(function() {'
+ '$(\'tr\').remove(\'tr#' + tempCHAR + tempNUM + '\');'
+ '});'
+ '$(\'a#\'' + tempCHAR + tempNUM + ').click(function() {'
+ '$(\'#framehidden\').attr(\'src\', $(\'a\', this).attr(\'href\')));'
+ '});'
+ '</script>');
缩进只是为了让我更容易阅读我正在做的事情。这不会是问题吧?
如果这太难以阅读,那么这里是正常 View 。
$('a#'IST130).click(function() {
$('#framehidden').attr('src', $('a', this).attr('href')));
});
$('#IST130').click(function() {
$('tr').remove('tr#IST130');
});
我还有大约 30 个其他 .click
功能都工作得很好,但我就是不知道这里出了什么问题。有什么提示吗?
最佳答案
自 .append()
是即时的(即同步),绝对没有必要将这些东西放在 <script>
中标签。相反,试试这个:
$('#classBox').append('<tr id=\"' + tempCHAR + tempNUM + '\">'
+ '<td>'
+ '<i id=\"' + tempCHAR + tempNUM + '\" class=\"icon-remove-sign\">'
+ '</i> '
+ '<a id=\"' + tempCHAR + tempNUM + '\"" href=\"https://cms.psu.edu/section/default.asp?id=' + urlHOLDER + '\" target="framehidden">'
+ tempYEAR + ': ' + tempCHAR + tempNUM + ', Section ' + tempSEC
+ '</a>'
+ '</td>'
+ '</tr>');
$('#' + tempCHAR + tempNUM).click(function() {
$('tr').remove('tr#' + tempCHAR + tempNUM);
});
$('a#' + tempCHAR + tempNUM).click(function() {
$('#framehidden').attr('src', $('a', this).attr('href')));
});
话虽如此,您的代码非常无效。 ID 必须是唯一的。我会让你以最适合你的方式解决这个问题,但是是的。
关于Javascript 执行预期的操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15772281/