【问题标题】:Change innerhtml of all h2 elements within div更改 div 中所有 h2 元素的 innerhtml
【发布时间】:2012-09-27 19:14:53
【问题描述】:

这可能是一个愚蠢的错误,但我似乎无法让它工作。 我正在尝试使用 id=variable id 的 div 更改所有 H2 元素的 innerhtml。

var numberOfQuestions = $('.question').length;
  var id = "question"+(numberOfQuestions);
  clone.id=id;
  document.documentElement.getElementById(id).getElementsByTagName( "h2" ).innerhtml= "Question"+(numberOfQuestions);

我认为我在这里做错了:document.documentElement.getElementById(id).getElementsByTagName( "h2" ).innerhtml= "Question"+(numberOfQuestions); nrtire 脚本:

 <script type="text/javascript">

function copyAppendRow() {
  var question = document.getElementById("question");
  var clone=question.cloneNode(true);
  var numberOfQuestions = $('.question').length;
  var id = "question"+(numberOfQuestions);
  clone.id=id;
  var questiondiv = document.getElementById(id);
var h2s = questiondiv.getElementsByTagName("h2");
for(var h = 0; h < h2s.length; h++ ) {
  h2s[h].innerHTML = "Question"+(numberOfQuestions); }
  if($('#questionsuccess').css('display') == 'none'){
  $('#questionsuccess').fadeIn('fast');
 $('#questionsuccess').fadeOut(4000);
  }
  }

</script>

【问题讨论】:

    标签: javascript innerhtml


    【解决方案1】:

    你的意思是这样的:

    var divEle = document.getElementById("yourDivId");
    var h2s = divEle.getElementsByTagName("h2");
    for(var h = 0; h < h2s.length; h++ ) {
      h2s[h].innerHTML = "Question"+(numberOfQuestions);
    }
    

    或 jQuery方式:

    $("#"+yourDivId + " > h2").html("Question"+(numberOfQuestions));
    

    【讨论】:

    • 似乎是对的。但似乎不起作用。我已经添加了我的完整脚本,因此您可以查看他们是否有任何问题。谢谢。
    • 哇哦。在某些时候,我删除了脚本的附加部分。你的完美。谢谢
    【解决方案2】:

    我从您的第一行中看到您已经在使用 jQuery,所以让自己的生活变得轻松并使用它来完成这项任务。

    $('#' + id + ' h2').html( 'Question ' + numberOfQuestions );
    

    jQuery 选择器的工作方式与 CSS 选择器类似。因此,这行代码会找到以您的变量 id 作为其 id 的元素,并获取该元素中的所有 h2 标记。 .html 是一个设置元素内部 HTML 的 jQuery 方法。

    【讨论】: