使用jQuery html()创建自闭元素时会出现以下问题:
$('#someId').html('<li><input type="checkbox" /></li>')
Run Code Online (Sandbox Code Playgroud)
将创造
<li><input type="checkbox"></li>
Run Code Online (Sandbox Code Playgroud)
它正确关闭<li>标签但不关闭<input>
这似乎是来自html()函数中使用的innerHTML的一个问题.
我已经到处寻找并为此找到了解决方案但是该页面不再可用,如您所见:http://dev.jquery.it/ticket/3378
有谁知道如何解决这个问题?
如果我有这样的span标签:
<span>Hi<br />SecondLine</span>
Run Code Online (Sandbox Code Playgroud)
我称之为jQuery函数:
var html = $('span').html();
Run Code Online (Sandbox Code Playgroud)
html设置为:
Hi<br>SecondLine
Run Code Online (Sandbox Code Playgroud)
现在,我意识到函数的名称是html()而不是xhtml().但这是预期的行为吗?我可以指望它,或者我总是需要检查xhtml br标签和html br标签,例如,这个例子:
function br2nl(text) {
return text.replace(/<br \/>/gi, '\n').replace(/<br>/gi, '\n');
}
Run Code Online (Sandbox Code Playgroud) 有没有一种方法可以在jQuery中找到jQuery中的文本字符串,而不是用其他东西替换它,但是用一个元素包装该文本,这样当脚本完成时,它会用文本字符串包裹原始文本.
例:
原文
"Hello world to all people"
Run Code Online (Sandbox Code Playgroud)
搜索字符串
"world to"
Run Code Online (Sandbox Code Playgroud)
用...来代替 <i></i>
最终输出
"Hello <i>World to</i> all people"
Run Code Online (Sandbox Code Playgroud)
在此先感谢您的帮助!
一种工作代码:
function highlightChild(child) {
$(childElements[child]).text("");
console.log(child);
$('.child_element_' + child).bind('textselect', function(e){
var selection = e.text;
var str = $("#construct_version").text();
var wrap = jQuery(childElements[child]).text(selection);
var re = new RegExp("" + selection + "", "g");
console.log(str.replace(selection, function(match, key, val){
console.log(match);
console.log(key);
console.log(val);
jQuery(childElements[child]).text(val)
}));
});
}
Run Code Online (Sandbox Code Playgroud)
上面的代码执行替换,但它实际上替换它显示为undefined.
因此,如果原始字符串是所有人的Hello world并且我想要将world替换为with <b>world to</b>,则它在console.log中显示为Hello undefined all