在 jQuery 中寻址父 DOM


Addressing the Parent DOM in jQuery

我有一个网页,它使用简单的查询根据数据库中的类别生成了相同的 DIV。所以在这种情况下,有两个类别。 每个 DIV 都有一个按钮,单击该按钮时应更改当前 DIV 标题文本的文本。

<body>
<div class="DOMParent" style="width: 100%; border: 1px solid #ff0000; margin: 10px; padding:10px;">
    <div class="title">
        <div class="titleText">Category 1</div>
        <button id="btn">id="btn" Click Me</button>
    </div>
</div>
<div class="DOMParent" style="width: 100%; border: 1px solid #ff0000; margin: 10px; padding:10px;">
    <div class="title">
        <div class="titleText">Category 2</div>
        <button id="btn">id="btn" Click Me</button>
    </div>
</div>

<script>
    dp("#btn").click(function(){
        dp(".titleText").html("This is the new TITLE Text");
    });
</script>
</body>

我的问题是,例如,在类别 1 中,如果我单击该按钮,那么它将更改两个标题文本的 html,而它应该只更改类别 1 中标题文本的 html。

我尝试使用增量ID和各种绝对不是答案。那么如何仅在按钮的当前 DOMParentdiv 中更改标题文本呢?

编写此示例代码只是为了简化我的问题,使代码小得多。我省略了 mysql 查询和排序,因为最终这实际上是生成的。

id 属性

是唯一值,因此您需要将按钮 id 属性更改为

<button class="btn"> Click Me</button>

现在你想访问 parent,所以你应该使用 jQuery 的 parent() 方法。 然后你需要用 find 方法.titleText子项。

所以你可以写这样的代码,并检查下面的示例小提琴

$(this).parent().find(".titleText").text("This is the new TITLE Text");

由于"ID 必须是唯一的",您可以像这样为button提供一个通用class

<div class="DOMParent" style="width: 100%; border: 1px solid #ff0000; margin: 10px; padding:10px;">
<div class="title">
    <div class="titleText">Category 1</div>
    <button class="btn">id="btn" Click Me</button>
</div>
</div>
<div class="DOMParent" style="width: 100%; border: 1px solid #ff0000; margin: 10px; padding:10px;">
<div class="title">
    <div class="titleText">Category 2</div>
    <button class="btn">id="btn" Click Me</button>
</div>

然后在 JS 中使用 prev 来获取以前的div,如下所示class titleText

dp(".btn").click(function(){ 
    dp(this).prev(".titleText").html("This is the new TITLE Text");
});

.prev() 方法在 DOM 树中搜索每个元素的前身,并从匹配的元素构造一个新的 jQuery 对象。

该方法可以选择接受可传递给 $() 函数的相同类型的选择器表达式。如果提供了选择器,则前面的元素将通过测试它是否与选择器匹配来过滤。

这是相同的演示

你必须对按钮而不是 id 使用 class,并找到它的兄弟姐妹。

<body>
<div class="DOMParent" style="width: 100%; border: 1px solid #ff0000; margin: 10px; padding:10px;">
<div class="title">
    <div class="titleText">Category 1</div>
    <button class="btn">id="btn" Click Me</button>
</div>
</div>
<div class="DOMParent" style="width: 100%; border: 1px solid #ff0000;  margin: 10px; padding:10px;">
<div class="title">
    <div class="titleText">Category 2</div>
    <button class="btn">id="btn" Click Me</button>
</div>
</div>

<script>
$("#btn").click(function() {
  $(this).siblings(".titleText").html("This is the new TITLE Text");
});
</script>
</body>