2013-08-20 48 views
0

我有一個父錨鏈接與許多子跨度元素。當用戶點擊跨度時,我執行不同的操作。jquery點擊檢測目標孩子

此刻我簡單地關閉默認點擊行爲,然後綁定我的自定義點擊。 如何將它合併爲一個點擊功能?或者是正確的處理方式?

<a href='http://www.test.com' target='_blank'><span>Link</span> other non clickable text</a> 

// Bind menu items 
$('a').each(function() { 
    var $item = $(this); 

    // Turn off default click 
    $item.click(function(){ 
    return false; 
    }); 

    // Click label text 
    $item.children('span').eq(0).click(function(e){ 
    e.preventDefault(); 
    e.stopPropagation(); 
    if($item.attr("href")) { 
     //window.location = '//' + $item.attr("href"); 
     alert('window.location'); 
    } 
    }); 

}); // each 

http://jsbin.com/oFeMIPI/2/?html,js,output

回答

1

另一種方法使用委派事件

$('a').on("click","span",function(e){ 
    //this now refers to the clicked span 
    //do your logic here. 

    return false; 
}); 
0

認爲自己可能會在想着它,只需做到這一點:

$("a span").click(function(e) { 
    e.stopPropagation(); //Stop bubbling 
    e.preventDefault(); //Dont execute default link behavior 

    //Log stuff that you need! 
    console.log("Link: " + $(this).parent().attr("href")); 
    console.log("Span Text: " + $(this).text()); 
}); 

演示:http://jsfiddle.net/Dhne7/

0

嘗試

$('a').click(function(e){ 
    var $item = $(this), $target = $(e.target); 

    if($target.is('span')){ 
     console.log($item.attr('href')) 
    } 


    return false; 
}) 

演示:Fiddle