如何使用JQuery获取html元素(PartialView)的祖先元素

How to take by JQuery the ancestor-element of an html-element(PartialView)?

本文关键字:元素 PartialView 祖先 JQuery 获取 html 何使用      更新时间:2023-09-26

我想取tag的祖先标签。

删除位于部分视图

我能够通过AJAX将部分视图加载到视图中。但是,我不能使用分部视图的祖先来操作分部视图,在我的例子中,就是删除分部视图。

My partial View is:

<img id="hello" src="@Url.Content("/content/images/" + @Model.Address)" />
<br />
<a id="linkToDel" onclick="clickme(this.id)">Delete</a> 

View is:

<div id="imageDivFirst"></div>

JavaScript加载局部视图:

$('#imageDivFirst').load('/Home/ImagePartialView', { address: data.result.name });

我试图得到一个祖先的部分视图:

function clickme(id) {
var a = document.getElementById("linkToDel").previousElementSibling.previousSibling.previousSibling;// not detected an ancestor
} 
//then I want to take an ancestor of <a id="linkToDel"/> 
// and delete the partial view

如何获得这个位于View的祖先:

<div id="imageDivFirst"></div>//How to get this ancestor located at View?

可以传递元素引用

<a id="linkToDel" onclick="clickme(this)">Delete</a> 
然后

function clickme(el) {
    var a = el.parentNode;//parent element
    $(el).parent().remove();//using jQuery to remove the parent element
    $(el).parent().empty();//to remove the partial contents only, but the parent element will remain
} 

在jquery中可以使用closest():

$("#linkToDel").closest("#imageDivFirst")

但要确保你的html中没有多个具有相同id的元素,否则会产生问题,如果可以有多个元素,那么使用元素的class属性而不是id。