使用Jquery

时间:2016-11-23 03:18:03

标签: javascript jquery html

在我的js函数中,我想更改div中某些元素的属性,然后我需要将该div的html内容传递给另一个函数。但是,我使用html()方法获得的html没有改变。如何在更改后获取html?代码如下所示:

function copyDiv() {
  //set the content of the textarea
  $('#text_field').val("test");
  
  //get the content of the textarea, the content is changed
  alert($('#text_field').val());
        
  //get the html content and set it to the new div
  //However, this html is not changed
  $('#newDiv').html( $('#myDiv').html());
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="myDiv">
  <label for="text_field">text: </label>
	
  <textarea class="form-control" id="text_field"></textarea>
</div>

<div id='newDiv'>
</div>

<button type="button" onclick="copyDiv();">test</button>

3 个答案:

答案 0 :(得分:1)

我修改了你的代码,在复制HTML后将textarea的值复制到新的textarea,因为这个值不是DOM的一部分(并且不会自动出现)。

我还从textarea中删除了ID属性,因为在一个页面上不能有多个元素具有相同的ID,这是您的代码产生的。

function copyDiv() {
  $formControl = $('#myDiv .form-control');

  //set the content of the textarea
  $formControl.val("test");
  
  //get the content of the textarea, the content is changed
  alert($formControl.val());
        
  //get the html content and set it to the new div
  $('#newDiv').html( $('#myDiv').html());
  $('#newDiv .form-control').val( $formControl.val() );
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="myDiv">
  <label for="text_field">text: </label>
	
  <textarea class="form-control" name="text_field"></textarea>
</div>

<div id='newDiv'>
</div>

<button type="button" onclick="copyDiv();">test</button>

答案 1 :(得分:0)

使用 jQuery.clone()代替 .html()

替换此

$('#newDiv').html( $('#myDiv').html());

是这个

$('#newDiv').html( $('#myDiv').clone());

答案 2 :(得分:-1)

  • 您可以尝试以下代码,如果您想在文本区域内设置内容,则应使用此代码$('#text_field').text("test");并设置文本区域的内部文本。
  • 如果您想更改value属性,可以使用此代码$('#text_field').attr("value","test");。其余代码是相同的。

&#13;
&#13;
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Tring Reset</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="myDiv">
  <label for="text_field">text: </label>
	
  <textarea class="form-control" id="text_field"></textarea>
</div>

<div id='newDiv'>
</div>

<button type="button" onclick="copyDiv();">test</button>	
<script>
function copyDiv() {
	  //set the content of the textarea
	  $('#text_field').text("test");
	  //to set the value attribute of th text area
	  $('#text_field').attr("value","test");
	  
	  //get the content of the textarea, the content is changed
	  alert($('#text_field').text());
	        
	  //get the html content and set it to the new div
	  //However, this html is not changed
	  $('#newDiv').html( $('#myDiv').html());
	}
</script>
</body>
</html>
&#13;
&#13;
&#13;