折腾:
【未解决】给绘本查询web版增加点击tag标签搜索
期间,遇到一个问题,对于html页面:
对于某个tag:
去加上了click事件的支持:
function tagClickCallback(event){ console.log("tagClickCallback: event=%o", event) console.log("this=%o", this) var clickedTagStr = $(this).text() console.log("clickedTagStr=%s", clickedTagStr) } $(document).on("click", ".book_list_single_tag", tagClickCallback)
但是调试才发现,想起来:
之前对于此tag所处于的父级元素,整个div,原先也是已经支持了点击事件的:
function saveInputAndRedirect(event){ console.log("saveInputAndRedirect: event=%o", event) console.log("this=%o", this) var curInput = $("#inputQuery").val() console.log("curInput=%s", curInput) event.data = { "curInput": curInput, "curElement": this, } console.log("event.data=%o", event.data) // redirectToDetailPage.bind(this) redirectToDetailPage(event) } $(document).on("click", ".single_storybook_item", saveInputAndRedirect)
所以此时点击tag时,其实只有父级元素响应了click,导致内部元素tag没法响应click了。
希望:
对于外层,父级区域的元素,支持click点击,响应事件
同时,如果只是点击了tag所属区域,则响应tag的click的事件
html parent and child booth click
html parent child click
这个就是所谓的:event bubbling 事件冒泡(上报)
好像是:
点击child,则不上报event给parent,好像就可以了?
Event capturing When you use event capturing | | ---------------| |----------------- | element1 | | | | -----------| |----------- | | |element2 \ / | | | ------------------------- | | Event CAPTURING | ----------------------------------- the event handler of element1 fires first, the event handler of element2 fires last. Event bubbling When you use event bubbling / \ ---------------| |----------------- | element1 | | | | -----------| |----------- | | |element2 | | | | | ------------------------- | | Event BUBBLING | ----------------------------------- the event handler of element2 fires first, the event handler of element1 fires last.
试试:
event.stopPropagation()
给parent的single_storybook_item加上试试:
function saveInputAndRedirect(event){ event.stopPropagation() 。。。 } $(document).on("click", ".single_storybook_item", saveInputAndRedirect)
结果问题依旧:
点击了tag还是跳转到详情页
感觉错了?应该加到child的元素上?
去试试
function tagClickCallback(event){ event.stopPropagation() ... } $(document).on("click", ".book_list_single_tag", tagClickCallback)
结果:
是对的:
再去去掉parent中的event.stopPropagation,也是同样的正确的效果:
点击child区域,响应child的click事件:
点击parent的区域,响应parent的click事件
跳转新页面了:
【总结】
对于此处的:
<li class="list-group-item single_storybook_item"> ... <div class="media-body"> <p class="book_list_tags" data-difficulty="20"> <span class="badge badge-pill badge-secondary book_list_single_tag">Opposites and Contrasts</span> ... </p> </div> </div> </li>
parent是li的single_storybook_item
child是span的book_list_single_tag
各自都有click的event
希望实现:
click点击child的book_list_single_tag,只响应child的event,不触发parent的event
点击parent的single_storybook_item,正常响应parent的event
具体做法是:
只需要去child的click的event中,加上:
event.stopPropagation()
比如:
function tagClickCallback(event){ event.stopPropagation() ... } $(document).on("click", ".book_list_single_tag", tagClickCallback)
即可。