backbone.js 按类名查找最接近被单击按钮的文档元素

eqzww0vc  于 2022-11-10  发布在  其他
关注(0)|答案(1)|浏览(144)

我有一个小的迷你html游戏,使用 Backbone 。
主页有多个<div>标签,其类名为“monsterName”。
它旁边有一个按钮,单击该按钮时,我希望获得“monsterName”<div>中的文本
我尝试使用WebAPI中的closest()方法来查找与所单击的按钮最接近的类名为“monsterName”的<div>
这里这将帮助你看到我的HTML页面生成的视图和模板:

<div id="root">

<div id="title">Monster Hunting 101</div>

<div class="monsterArea">
    <div class="monsterName">Orc</div>
    <div class="controls">
        <button class="findMonster">Monster Hunting</button>
    </div>
</div>

<div class="monsterArea">
    <div class="monsterName">Dragon</div>
    <div class="controls">
        <button class="findMonster">Monster Hunting</button>
    </div>
</div>

<div class="monsterArea">
    <div class="monsterName">Giant</div>
    <div class="controls">
        <button class="findMonster">Monster Hunting</button>
    </div>
</div>

该视图包含在单击按钮“.findMonster”时触发的代码:

events: {
    "click .findMonster": "startHunt"
},

当单击该按钮时,它将触发此函数:

startHunt: function (e) {
    const $closestMonster = e.closest('.monsterName');
    console.log($closestMonster.innerHTML);
    ...do some stuff with the text in the monsterName...
}

因此,视图和按钮都正常工作,并触发了startHunt事件。
但它总是给我这个错误:未捕获的类型错误:也就是说,最接近的不是函数

u59ebvdq

u59ebvdq1#

closest()find()的组合可以解决此问题:

const $closestMonster = e.closest('.monsterArea').find('.monsterName');

相关问题