我有一个小的迷你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事件。
但它总是给我这个错误:未捕获的类型错误:也就是说,最接近的不是函数
1条答案
按热度按时间u59ebvdq1#
closest()
和find()
的组合可以解决此问题: