我有一个带有div的页面,如果点击它,就会出现一个文本输入框。
下面是一个最小的代码:
<html>
<head>
<script type="text/javascript" src="jquery-1.9.1.min.js"></script>
</head>
<body>
<div id="d1">a</div>
</body>
</html>
<script type="text/javascript">
$(document).ready( function(){
$( document ).on( "click", "#d1", function( e ){
$( this ).html( "<input type='text'>" );
} );
} );
</script>
问题是,尽管出现了文本输入框,但没有显示任何字符。
但是,如果我使用:
$( this ).replaceWith( "<input type='text'>" );
它的工作方式与预期一致。
此外,如果我将html添加到另一个元素中,它也会按预期工作,例如
$("#some_other_element").html( "<input type='text'>" );
这是一个bug,还是我遗漏了什么?
谢谢
发布于 2015-03-05 19:20:47
更改为以下内容:
$( this ).html("<input type='text' value='"+$(this).text().trim()+"'>");
发布于 2015-03-05 19:21:09
$(document).ready( function(){
$( document ).on( "click.yourEventName", "#d1", function( e ){
var $this = $(this);
var text = $this.text();
$this.html( $("<input>", {type: "text"}).val(text) );
$(document).off(".yourEventName");
} );
} );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<html>
<head>
<script type="text/javascript" src="jquery-1.9.1.min.js"></script>
</head>
<body>
<div id="d1">a</div>
</body>
</html>
https://stackoverflow.com/questions/28876552
复制相似问题