[英]Check to see if the target of a click contains several substrings
This seems relatively straightforward, but it's giving me trouble. 这似乎相对简单,但却给我带来麻烦。 I want to do something on all clicks that fit certain criteria so I start by putting this in the header: 我想对符合特定条件的所有点击执行某些操作,因此首先将其放在标题中:
<script type="text/javascript">window.onclick = function(e) {
alert(e.target);
};</script>
This alerts "www.chorizon.com/link?page=155". 这将提示“ www.chorizon.com/link?page=155”。 Now, this works: 现在,这有效:
<script type="text/javascript">window.onclick = function(e) {
var test="www.chorizon.com/link?page=155";
if((test.indexOf("link") > -1) && (test.indexOf("page=155") > -1)){
alert('yes')
}
};</script>
So why doesn't this work? 那为什么不起作用呢?
<script type="text/javascript">window.onclick = function(e) {
if((e.target.indexOf("link") > -1) && (e.target.indexOf("page=155") > -1)){
alert('yes')
}
};</script>
Is there something I need to do to e.target to use it like a regular string? 我需要对e.target进行某些操作以像常规字符串一样使用它吗?
The reason you're confused is because alert() is not a debugging tool , you're really getting an object containing a reference to a DOM element, not a string, it's just converted to a string as alert
can't display objects, and that object has no indexOf
method! 您感到困惑的原因是因为alert()不是调试工具 ,您实际上是在获取包含对DOM元素的引用的对象,而不是字符串,而是将其转换为字符串,因为alert
无法显示对象,而且该对象没有indexOf
方法!
Start using the console for debugging. 开始使用控制台进行调试。
Not sure what you're trying to get, but it looks like an URL, so I'm guessing it's the href property of an anchor, but that would redirect the page, hence the uncertainty ? 不确定您要获取的内容,但它看起来像URL,因此我猜想它是锚的href属性,但这会重定向页面,因此不确定吗?
document.addEventListener('click', function(e) {
var url = e.target.href || '';
if( url.indexOf("link") > -1 && url.indexOf("page=155") > -1) {
alert('yes')
}
}, false);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.