我希望获取<div>
中的文本或DOM属性的值,值为保卫科
,
但我总是得到undefined
或JS错误。
我是JS的新手。我正在尝试一些方法来获取div的文本,但我失败了。我需要帮助。
这个HTML片段是一个组织结构图,我现在遍历它以获得它所代表的结构并将结果值连接成一个json对象,但我不熟悉JS DOM操作,这让我整天困扰
function loop($chart) {
// var that = this;
//$chart是一个DOM
var $tr = $chart.find('tr:first');
//找到根结点 获取id id为1 拼接json
// console.log($tr);
console.log($tr.find('.node:first').innerText);
var subObj = { 'id': $tr.find('.node')[0].id ,'name':$tr.find('.node')[0].value};
//找到tr中的最后一个 记录子节点的tr 然后遍历
$tr.siblings(':last').children().each(
function () {
//如果subObj没有子节点 则创建一个数组装子节点
if (!subObj.subordinate) {
subObj.subordinate = [];
}
//往数组中push东西
subObj.subordinate.push(loop($(this)));
});
return subObj;
}
&#13;
<div id="orgchart" class="orgchart view-state">
<table>
<tr>
<td colspan="4">
<div id="1512554614742741" value="保卫处" class="node">
<div class="title">
<i class="fa fa-th-large symbol"></i>保卫处</div>
<i class="edge verticalEdge bottomEdge fa"></i>
</div>
</td>
</tr>
<tr class="lines">
<td colspan="4">
<div class="downLine"></div>
</td>
</tr>
<tr class="lines">
<td class="rightLine"> </td>
<td class="leftLine topLine"> </td>
<td class="rightLine topLine"> </td>
<td class="leftLine"> </td>
</tr>
<tr class="nodes">
<td colspan="2">
<table>
<tr>
<td colspan="2">
<div id="1512554614755264" data-parent="1" value="2部门" class="node">
<div class="title">
<i class="fa fa-th-large symbol"></i>2部门</div>
<i class="edge verticalEdge topEdge fa"></i>
<i class="edge horizontalEdge rightEdge fa"></i>
<i class="edge horizontalEdge leftEdge fa"></i>
<i class="edge verticalEdge bottomEdge fa"></i>
</div>
</td>
</tr>
<tr class="lines">
<td colspan="2">
<div class="downLine"></div>
</td>
</tr>
<tr class="lines">
<td class="rightLine"> </td>
<td class="leftLine"> </td>
</tr>
<tr class="nodes">
<td colspan="2">
<table>
<tr>
<td>
<div id="1512554614762739" data-parent="2" value="6部门" class="node">
<div class="title">6部门</div>
<i class="edge verticalEdge topEdge fa"></i>
</div>
</td>
</tr>
</table>
</td>
</tr>
</table>
</td>
<td colspan="2">
<table>
<tr>
<td>
<div id="1512554614773842" data-parent="1" value="4部门" class="node">
<div class="title">4部门</div>
<i class="edge verticalEdge topEdge fa"></i>
<i class="edge horizontalEdge rightEdge fa"></i>
<i class="edge horizontalEdge leftEdge fa"></i>
</div>
</td>
</tr>
</table>
</td>
</tr>
</table>
</div>
&#13;
答案 0 :(得分:0)
我试过它有效:
function myFunction() {
var x = document.getElementById("1512554614742741").getAttributeNode("value").value;
//here you have 保卫科 in x variable but it doesn't show anywhere on the page
//you choose what you want to do with it for example show it in the html page
}