DOM要素をクリックすると、その親要素に特定のクラスが含まれているかどうかを確認したいと思います。私はこのように試みていますが、この目標を達成することはできません。誰かが方法を知っていますか?
document.onclick=function(e){
console.log(e.parentElement('.drop').id);
}
JavaScriptでのみ解決策を提供してください-jQueryは使用できません。
DOM要素をクリックすると、その親要素に特定のクラスが含まれているかどうかを確認したいと思います。私はこのように試みていますが、この目標を達成することはできません。誰かが方法を知っていますか?
document.onclick=function(e){
console.log(e.parentElement('.drop').id);
}
JavaScriptでのみ解決策を提供してください-jQueryは使用できません。
classList
親要素のプロパティを使用できます。目的にcontains()
役立つメソッドがあります。
document.onclick=function(e){
console.log( e.parentElement.classList.contains( 'drop' ) );
}
Internet Explorer (IE<10) をターゲットにしている場合は、クラスのリストを手動で解析し、それらの「ドロップ」を探すことができます。
document.onclick=function(e){
console.log( e.parentElement.className.split(' ').indexOf('button-panel')!==-1 );
}
split()
className を配列内の複数の名前に解析します。
indexOf()
配列内の要素を検索し、見つからない場合は -1 を返します
イベント ハンドラーにe
渡されるのはイベント オブジェクトであり、クリックされた要素ではありません。をつかんでみるとsrcElement
、それは親のclassName
です。また、jQuery を使用できないため、.drop
前後のようにセレクターを渡しても何も実行されず、構文エラーが発生します。
document.onclick = function(e){
console.log(e.srcElement.parentNode.className);
e.stopPropagation(); // don't bubble
};
now i got the answer
document.onclick=function(e){
if (!e) e = window.event;
curDD = findparentClass(e.target.parentNode,'drop');
console.log(curDD);
}
}
function findparentClass(node, clsName) {
if(node.className != clsName && node.className!=null){
return findparentClass(node.parentNode,clsName);
}else if(node.className!=null){
return true;
}
}
「ドロップ」は検索するクラスです...