如何通过通用的onclick事件捕获div / span标记中的其他详细信息?
即
<span id=item1>Value #001<span id=clickableitem>xxx</span></span>
<span id=item2>Value #002<span id=clickableitem>xxx</span></span>
<span id=item3>Value #003<span id=clickableitem>xxx</span></span>
然后:
$(document).on('click','#clickableitem',function(e){
e.preventDefault();
// how do I get the "value #001, #002, #003" value just 'outside'
// of the span tag?
我试图用.parent()。html()弄清楚,但这似乎不太起作用...
谢谢!
答案 0 :(得分:0)
id属性应该始终是唯一的,而是为您的span提供一个通用的className,并在HTML中用它连接事件处理程序回调 您需要在属性的值(例如id和class)周围加上单引号或双引号:
HTML:
<span id='item1'>Value #001<span id='clickableitem1' class='spanClickable'>xxx</span></span>
<span id='item2'>Value #002<span id='clickableitem2' class='spanClickable'>xxx</span></span>
<span id='item3'>Value #003<span id='clickableitem3' class='spanClickable'>xxx</span></span>
jQuery:
$(document).on('click','.spanClickable',function(e){
e.preventDefault();
//Using .text() on the parent produces the child span text as well
//Replace the child text and the word Value since all you want is
//ex. #001
const childSpanText = $(this).text();
alert($(this).parent().text().replace(childSpanText, "").replace('Value ', ''));
});
工作小提琴 (https://jsfiddle.net/a5Lkon4j/2/)
答案 1 :(得分:0)
HTML:
<span id=item1>Value #001<span class="clickableitem">xxx</span></span>
<span id=item2>Value #002<span class="clickableitem">xxx</span></span>
<span id=item3>Value #003<span class="clickableitem">xxx</span></span>
JS:
$('.clickableitem').click(function() {
let text = $(this).parent().text().substring(0, $(this).parent().text().indexOf($(this).text()));
console.log(text);
});
答案 2 :(得分:0)
如果值与xxxx子跨度相同,则替换文本不安全可能会导致文本为空。...
此方法更有效
HTML
<span id='item1'>Value #001<span id='clickableitem1' class='spanClickable'>xxx</span></span>
<span id='item2'>Value #002<span id='clickableitem2' class='spanClickable'>xxx</span></span>
<span id='item3'>Value #003<span id='clickableitem3' class='spanClickable'>xxx</span></span>
JS
$(document).on('click','.spanClickable',function(e){
alert( $(this).parent().contents().get(0).nodeValue );
});