如何检查链接目标是否为iframe

时间:2018-12-24 21:26:31

标签: javascript

请参见以下示例:

document.addEventListener('click', function(e){
  if(e.target.tagName == 'A'){
    e.preventDefault();
    if(true){
      console.log('Target is an iframe');
    } else {
      console.log('Target is not an iframe');
    }
  }
});
<a href="about:blank">1</a>
<a href="about:blank" target="iframe">2</a>
<a href="about:blank" target="not_iframe">3</a>
<iframe name="iframe" src="about:blank" style="display: none;"></iframe>

我在其中放置了if(true)作为占位符。我实际上如何检查被点击链接的目标是iframe还是不是iframe?

谢谢!

3 个答案:

答案 0 :(得分:2)

您可以检查是否存在具有该名称的[ { "CATEGORY_ID":1, "CATEGORY_NAME":"FURNITURE", "DESCRIPTION":"INDOOR FURNITURE" }, { "CATEGORY_ID":2, "CATEGORY_NAME":"AUTOMOBILES", "DESCRIPTION":"CARS, BIKES" }, { "CATEGORY_ID":3, "CATEGORY_NAME":"LAPTOP & ACCESSORIES", "DESCRIPTION":"LAPTOP, MOUSE, KEY BOARD, PENDRIVE" } ]

iframe
document.addEventListener('click', function(e){
  if(e.target.tagName == 'A'){
    var target = e.target.target;
    var iFrameExist = document.querySelector(`iframe[name="${target}"]`);
    if(iFrameExist){
      console.log('Target is an iframe');
    } else {
      console.log('Target is not an iframe');
    }
    return false;
  }
});

答案 1 :(得分:0)

我已经扩展了您的代码以执行您希望的操作。首先,您应该检查clicked标签的target成员,如果存在,则要搜索具有该名称的元素(不知道为什么不使用ID)。最后,使用找到的元素,并检查第一个元素是否为iframe。

document.addEventListener('click', function(e){
  if(e.target.tagName == 'A'){
    e.preventDefault();
    let tag = e.target;
    
    if (tag.target) {
      let found = document.getElementsByName(tag.target);
      
      if (found.length > 0) {
        let potential = found[0];
        
        if (potential.tagName == "IFRAME") {
          console.log("Target is an iframe");
        } else {
          console.log("Target is not an iframe");
        }
      } else {
          console.log("No element with matching name found!");
      }
    } else {
      console.log("No target set");
    }
  }
});
<a href="about:blank">1</a>
<a href="about:blank" target="iframe">2</a>
<a href="about:blank" target="not_iframe">3</a>
<a href="about:blank" target="isdiv">4</a>
<iframe name="iframe" src="about:blank" style="display: none;"></iframe>
<div name="isdiv">

</div>

答案 2 :(得分:0)

我找到了一个非常简单的解决方案:

document.addEventListener('click', function(e){
  if(e.target.tagName == 'A'){
    e.preventDefault();
    if(window.frames[e.target.target]){
      console.log('Target is an iframe');
    } else {
      console.log('Target is not an iframe');
    }
  }
});
<a href="about:blank">1</a>
<a href="about:blank" target="iframe">2</a>
<a href="about:blank" target="not_iframe">3</a>
<iframe name="iframe" src="about:blank" style="display: none;"></iframe>