我一直在编写一个脚本来从页面上的一个div中获取文本并将其输入到另一个div中。我遇到了一个奇怪的问题。当我提醒我的FillinId变量时,我想出了questionTextF。但是,当我尝试在我的下一个变量GrabFillinDiv中使用该值时,该值返回null。如果我手动输入questionTextF,一切正常。我不能这样做,因为有多个FillinId可以从中获取内容。
这是一个JSFiddle: http://jsfiddle.net/hzbdhxvs/
这是我的Javascript:
$(document).ready(function(){
var QuestionTypeName = "MultipleListQuestion-test";
var FillinDivParent = document.getElementById(QuestionTypeName);
var FillinDivChildren = FillinDivParent.getElementsByTagName("div");
for (i=0; i< FillinDivChildren.length; i++){
var FillinId = $(FillinDivChildren[i]).attr("id");
alert(FillinId);
var TplId = FillinId.slice(0,-1);
var GrabFillinDiv = document.getElementById("\"" + FillinId + "\"");
var GrabFillinText = $("\"" + "#"+ FillinId + "\"").html();
alert(GrabFillinDiv.innerHTML);
$("\"" + "#"+ TplId + "\"").html(GrabFillinText);
}
});
答案 0 :(得分:1)
您在ID之前和之后添加了一些引号。不要这样做:
for (i=0; i< FillinDivChildren.length; i++){
var FillinId = $(FillinDivChildren[i]).attr("id");
alert(FillinId);
var TplId = FillinId.slice(0,-1);
var GrabFillinDiv = document.getElementById(FillinId);
var GrabFillinText = $("#"+FillinId).html();
$("#"+ TplId).html(GrabFillinText);
}
var QuestionTypeName = "MultipleListQuestion-test";
var FillinDivParent = document.getElementById(QuestionTypeName);
var FillinDivChildren = FillinDivParent.getElementsByTagName("div");
for (i=0; i< FillinDivChildren.length; i++){
var FillinId = $(FillinDivChildren[i]).attr("id");
alert(FillinId);
var TplId = FillinId.slice(0,-1);
var GrabFillinDiv = document.getElementById(FillinId);
var GrabFillinText = $("#"+FillinId).html();
$("#"+ TplId).html(GrabFillinText);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="care-questionType">
<form role="form">
<div id="questionText">
</div>
<div id="PrimaryResponseItemList">
<div class="checkbox" data-repeat="responseItem" id="">
<label id="ResponseLabel">
<input id="ResponseCheckBox" type="checkbox" value=""/>
</label>
</div>
</div>
<div id="OtherResponseItem">
<p id="OtherResponseLabel" ></p>
<div class="input-group">
<label class="input-group-addon">
<input id="OtherCheckBox"type="checkbox">
</label>
<input type="text" id="ResponseOtherSpecifyText" class="form-control-inline care-multipleSelect-otherText" />
</div>
</div>
</form>
</div>
<div style="display:none;">
<div id="MultipleListQuestion-test">
<div id="questionTextF">
<p>Which categories best describe your racial background? (Please choose all that apply)</p>
</div>
<div id="responseItemF" data-repeat="true">
<p>test</p>
<div id="ResponseLabelF">
American Indian or Alaskan Native
</div>
</div>
</div>
</div>
答案 1 :(得分:1)
摆脱"\""
插入。而不是
var GrabFillinDiv = document.getElementById("\"" + FillinId + "\"");
var GrabFillinText = $("\"" + "#"+ FillinId + "\"").html();
尝试:
var GrabFillinDiv = document.getElementById(FillinId);
var GrabFillinText = $("#"+ FillinId).html();