2017-06-08 63 views
-3

我正在尝试使用jQuery来获取子元素的文本。获取儿童文本的jQuery代码

我一定在做错事,现在已经做了两天了。

如果有人有时刻看一看,我会非常感激!

CODE:

function generateRemoveSectionDropDown() { 
    var dropDown = document.getElementById('RemoveSectionId'); 
    var agendaDiv = $("[name='agenda-nestable']"); 
    var agendaSections = $(agendaDiv).find("ol#agenda-root>li"); 
    for (var i = 0; i < agendaSections.length; i++) { 
     var optValue = null; 
     var optText = null; 
     var section = agendaSections[i]; 
     var sectionChildren = $(agendaSections[i]).children(); 
     for (var j = 0; j < sectionChildren.length; j++) { 
      alert('The text from child is: ' + sectionChildren[j].text); 
      optValue = j; 
      optText = sectionChildren[j].text; 
     } 

     var opt = document.createElement('option'); 
     opt.value = optValue; 
     opt.innerText = optText; 
     dropDown.appendChild(opt); 
    } 
} 

普拉克:http://plnkr.co/edit/jLi9epblNAtMbzezcRSY?p=preview(如果你点击 “运行方式”,我的代码将运行)

注:更新code.I已被黑客攻击围绕着它,把它恢复到一个良好的状态。

+0

如果您已经在使用jQuery,为什么'document.getElementById('?保持方法一致。 – Rajesh

+0

@Rajesh我尝试了纯粹的JavaScript和jQuery,都无法使其工作。 –

+0

你在哪里定义'sectionListItem'? – Niklas

回答

1

尝试使用任一纯(JavaScript的/ jQuery的)

工作实施例: -

function generateRemoveSectionDropDown() { 
 
    $("[name='agenda-nestable'] ol#agenda-root>li").each(function(){ // iterate over li 
 
    $('#RemoveSectionId').append('<option value=' + $(this).attr('id') + '>' + $(this).children('div').text() + '</option>');//create options and append to select-box 
 
    }); 
 
}
<!DOCTYPE html> 
 
<html> 
 

 
<head> 
 
    <script data-require="[email protected]*" data-semver="3.1.1" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> 
 
    <link rel="stylesheet" href="style.css" /> 
 
    <script src="script.js"></script> 
 
</head> 
 

 
<body> 
 
    <h1>Hello Plunker!</h1> 
 
    <div class="dd" name="agenda-nestable" id="nestable"> 
 
    <ol id="agenda-root" class="dd-list"> 
 
     <li class="dd-item" id="2879"> 
 
     <div class="dd-handle">Section123</div> 
 
     </li> 
 
     <li class="dd-item" id="2880"> 
 
     <div class="dd-handle">Section 4</div> 
 
     </li> 
 
     <li class="dd-item" id="2881"> 
 
     <div class="dd-handle">Section 5</div> 
 
     </li> 
 
    </ol> 
 
    </div> 
 
    <button value onclick='generateRemoveSectionDropDown()'>Run method</button><br/><br/> 
 
    <select id="RemoveSectionId"></select><!-- need to add it --> 
 
</body> 
 

 
</html>

+1

谢谢!这就像一个冠军。一旦StackOverflow允许,我将尽快接受答案。 –

1

使用的foreach(每个)功能,

试试下面的代码

function generateRemoveSectionDropDown() { 
     var dropDown = document.getElementById('RemoveSectionId'); 
     var agendaDiv = $("[name='agenda-nestable']"); 
     var agendaSections = $(agendaDiv).find("ol#agenda-root>li>div"); 
     //console.log(agendaSections); 

     agendaSections.each(function() { 
      console.log($(this).html()); 

       // add your set of code 

     }); 
}