我希望在点击它时获得元素的id(或类)。 我写这个代码。
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('*').click(function() {
var idName = $(this).attr('class');
alert(idName);
});
});
</script>
<div class="test">
<div class="test1">
<div class="test2">
test
</div>
</div>
</div>
但是它给了我父类的类(id)。(和undefined) 我怎么能删除它?(给我一个元素的类(或id))
答案 0 :(得分:1)
添加 override func loadView() {
super.loadView()
self.webView.navigationDelegate = self
self.webView.UIDelegate = self //must have this
}
并使用func webView(webView: WKWebView,
createWebViewWithConfiguration configuration: WKWebViewConfiguration,
forNavigationAction navigationAction: WKNavigationAction,
windowFeatures: WKWindowFeatures) -> WKWebView? {
if navigationAction.targetFrame == nil {
var url = navigationAction.request.URL
if url.description.lowercaseString.rangeOfString("http://") != nil || url.description.lowercaseString.rangeOfString("https://") != nil || url.description.lowercaseString.rangeOfString("mailto:") != nil {
UIApplication.sharedApplication().openURL(url)
}
}
return nil
}
:
event.stopPropagation
答案 1 :(得分:1)
对于类使用.attr('class')
,为{id}使用.attr('id')
。我在下面更新了你的例子。
单击某个元素时,单击将向下传播所有包含元素,并将触发每个元素的单击功能。要停止传播,请使用.stopPropagation()
。
$().ready(function() {
$('*').click(function(e) {
var classNames = $(this).attr('class');
var idName = $(this).attr('id');
alert('ID: ' + idName + '\r\nClasses: ' + classNames);
e.stopPropagation();
});
});
#a {
width: 200px;
height: 100px;
}
div {
border: 2px solid black;
border-sizing: border-box;
padding: 4px;
}
#a div {
width: 100%;
height: 100%;
}
.test {
background-color: green;
}
.test1 {
background-color: red;
}
.test2 {
background-color: orange;
}
.class1 {
text-decoration: underline overline;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<div id="a" class="test">test
<div id="b" class="test1 class1">test1
<div id="c" class="test2 class1">
test2
</div>
</div>
</div>
答案 2 :(得分:1)
或者只为每个元素显示id:
$('*').click(function(event) {
event.stopPropagation();
var ident = $(event.target).attr('id');
alert("id = " + ident);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="button">button</button>
<br>
<br>
<input type="textbox" id="textbox" placeholder="textbox" />
<br>
<br>
<span id="text">text</span>