parentNode未定义为tr

时间:2016-06-18 15:36:04

标签: javascript jquery

当它到达this.parentNode.removeChild(this);

我收到错误

  

this.parentNode未定义

在调试器中,我在该语句的开头暂停,看到“this”是:Object[ tr#CMD01.selected ]这正是我所期望的。 parentNode是如何定义的?我已经在这里搜索了很多类似的问题并继续查找“this”不正确的情况,但在我的情况下,它由调试器验证。

 $(document).ready(function() {
    	$.fn.deleteThisRow = function() {
    		this.parentNode.removeChild(this);
    	};
    });
    
    function deleteRow() {
    	$("#theList tr.selected").deleteThisRow();
    }
.selected {
		background-color: yellow
	}	
    <body>
    	<center id='bg'>
    	<table id="cmdList"> 
    		<thead>
    			<tr id="hdrow">
    				<th>Col1</th>
    				<th>Col2</th>
    				<th>Col3</th>
    			</tr>
    		</thead>
    		<tbody id="theList">
    			<tr id="CMD00">
    				<td>A1</td>
    				<td>A2</td>
    				<td>A3</td>
    			</tr>
    			<tr id="CMD01" class="selected">
    				<td>B1</td>
    				<td>B2</td>
    				<td>B3</td>
    			</tr>
    			<tr id="CMD02">
    				<td>C1</td>
    				<td>C2</td>
    				<td>C3</td>
    			</tr>
		</tbody>
	</table> 
	<table id="buttons">
		<tr>
			<td>
				<button onclick='deleteRow()'>Delete</button>
			</td>
		</tr>
	</table>
	</center>
    </body>

1 个答案:

答案 0 :(得分:4)

实现jQuery方法时,this的值在调用时将是jQuery对象,而不是DOM对象。因此,this.parentNode不存在,因为jQuery对象没有该名称的属性。

您可以使用jQuery的.parent(),也可以获取实际的DOM节点,然后使用.parentNode

如果您只打算一次处理单个DOM对象,则可以执行以下操作:

$.fn.deleteThisRow = function() {
    this[0].parentNode.removeChild(this[0]);
};

如果你的jQuery对象中可能有多个对象,那么你可以这样做:

$.fn.deleteThisRow = function() {
    this.remove();
};

或者,正如您可能注意到的那样,您甚至不需要自定义方法。如果你有一个jQuery对象,你可以直接在它上面调用.remove()

function deleteRow() {
    $("#theList tr.selected").remove();
}
相关问题