javascript - 如果元素在javascript中点击了parant,如何仅选择孩子
问题描述
我想通过在 webview 中触摸元素代码并将代码发送到我的应用程序来获取元素代码。我实现了这一点,但是每当我单击具有像 div 这样的参数的元素时,它们都被选中
**Java代码**
final WebSettings settings = myWebView.getSettings();
settings.setJavaScriptEnabled(true);
myWebView.setWebViewClient(new WebViewClient() {
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
final String injectedJs = "javascript:(function(){" + injectedJs() + "})()";
myWebView.loadUrl(injectedJs);
}
});
myWebView.addJavascriptInterface(
new Object() {
@JavascriptInterface
public void onClick(String param) {
Toast.makeText(MainActivity.this, param, Toast.LENGTH_LONG).show();
}
},
"appHost"
);
myWebView.loadUrl("file:///android_asset/data.html");
Javascript代码
var lastSelectedItem = null;
var showHighlighted = function(/* HTML element */view, /*boolean */highlighted) {
if (view) {
view.style.cssText = highlighted? 'background-color: #ADD8E6; ' :' ';
}
};
/* This new method, _addEventListener and _eventClick are the same as yours */
Object.prototype.each = function (fn, bind) {
for (var i = 0; i < this.length; i++) {
if (i in this) {
fn.call(bind, this[i], i, this);
}
}
};
var _addListener = document.addEventListener || document.attachEvent,
_eventClick = window.addEventListener ? 'click' : 'onclick';
/* I changed the element selection criteria, but you can change it back easily.
I am adding event listeners all the leaf elements in the DOM. */
var elements = document.body.getElementsByTagName('*');
elements.each(function (el) {
_addListener.call(el, _eventClick, function () {
/* First, deal with the previously selected item*/
showHighlighted(lastSelectedItem, false);
/* Update the selected item reference */
lastSelectedItem = el;
/* Finally, deal with the previously selected item*/
showHighlighted(lastSelectedItem, true);
appHost.onClick(el.outerHTML.replace(el.innerHTML , ' '));
}, false);
});
正如您在图片中看到的那样,我单击按钮,代码同时获取按钮和 div 即使按钮有一个参数,我如何才能让它只获取按钮?
解决方案
推荐阅读
- mirth - 欢笑,每条消息后更改文件写入器目标
- c++ - 尽管 if 子句为假,但为什么会引发错误?
- spring - 如何在 Spring Boot 中访问 TomcatEmbeddedWebappClassLoader
- javascript - 是否可以创建一个带有一些已分配节点的 HTMLSlotElement 的新实例?
- javascript - 为什么我收到无效的配置对象。Webpack 已使用与 API 架构不匹配的配置对象进行初始化?
- python - 导入期间未定义名称
- javascript - 从大数组中查询/搜索的数据结构 10^6 大小,由对象组成,作为数组中的项目
- angular - 对图像滑块使用 Angular 动画
- reactjs - React Native,从异步函数更新useEffect中的状态时出现问题
- reactjs - React:向许多元素添加许多事件