我正在使用jQuery,在展开某个项目时添加了一些JavaScript。
但是,jQuery函数内的JavaScript代码导致其余的jQuery代码失效。
$(this).parent('li').find('.moreInfo').append('<script>alert("hello");</script>');
我该怎么做来解决这个问题?
我正在使用jQuery,在展开某个项目时添加了一些JavaScript。
但是,jQuery函数内的JavaScript代码导致其余的jQuery代码失效。
$(this).parent('li').find('.moreInfo').append('<script>alert("hello");</script>');
我该怎么做来解决这个问题?
针对JavaScript追加问题,请使用以下代码:
var str="<script>alert('hello');";
str+="<";
str+="/script>";
$(this).parent('li').find('.moreInfo').append(str);
否则,更好的选择是连接 li 元素的点击事件: $("ul#myList li").click(function(){
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "url to your content page",
data: "{}",//any data that you want to send to your page/service
dataType: "json",
success: function(msg) {
$(this).find('.moreInfo').append(msg);
}
});
});
$(document).ready(function() {
$("ul").each(function() {
var _list = this;
$(_list).find("li").click(function() {
var _listItem = this;
$(this).animate({ height: 20 }, 300);
$(this).append("<script type='text/javascript'>" + "$('.resultsParag').text('I am injected via JS and will not mess up the other JS you have written cause I am a good boy');" + "</" + "script>");
});
});
});
/script
前面添加 \
,这样可以解决你的问题。可以尝试像这样
$(this).parent('li').find('.moreInfo').append('<script>alert("hello");</' + 'script>');