Jquery在右键单击菜单项上获取唯一的css选择器或单击dom元素

时间:2017-05-29 05:45:30

标签: javascript jquery xpath css-selectors

我正在尝试在右键单击dom元素时提示正确的css选择器和xpath。我可以在右键单击显示菜单,但我阻止获取css选择器和xpath值。代码的输入将是任何网站源代码(右键单击网站,查看源代码)或示例具有一些类名的html代码。我有一个引用拉独特的CSS选择器here

有关如何在右键单击任何dom元素时获取唯一css选择器和xpath的任何指针?

我的小提琴是here

<h2>Copy paste source code</h2>
<textarea id="txtSrcCode"></textarea>
<input type="button" value="Load Page" id="btnLoadPage" />
<div id="divToBindSrcCode">

</div>

<ul class='custom-menu'>
  <li data-action="first">First thing</li>
  <li data-action="second">Second thing</li>
  <li data-action="third">Third thing</li>
</ul>

Jquery代码

$('#btnLoadPage').click(function() {
  $('#divToBindSrcCode').html($('#txtSrcCode').val()); // Laod dom on to the page
});

$(document).bind("contextmenu", function(event) {

  // Avoid the real one
  event.preventDefault();
  // Show contextmenu
  $(".custom-menu").finish().toggle(100).

  // In the right position (the mouse)
  css({
    top: event.pageY + "px",
    left: event.pageX + "px"
  });
});


// If the document is clicked somewhere
$(document).bind("mousedown", function(e) {
  // If the clicked element is not the menu
  if (!$(e.target).parents(".custom-menu").length > 0) {
    // Hide it
    $(".custom-menu").hide(100);
  }
});

// If the menu element is clicked
$(".custom-menu li").click(function() {
  var kk = $(this).val();
  // This is the triggered action name
  switch ($(this).attr("data-action")) {
    // A case for each action. Your actions here
    case "first":
      alert(kk);
      break;
    case "second":
      alert("second");
      break;
    case "third":
      alert("third");
      break;
  }

  // Hide it AFTER the action was triggered
  $(".custom-menu").hide(100);
});

2 个答案:

答案 0 :(得分:4)

@jeka5555的答案与css-selector-generator.js等库结合使用,然后使用MDN's xpath generator即可:

<html>
    <head>
        <script src="./css-selector-generator.js"></script>
        <script>
            function getXPathForElement(el, xml) {
                var xpath = '';
                var pos, tempitem2;

                while(el !== xml.documentElement) {
                    pos = 0;
                    tempitem2 = el;
                    while(tempitem2) {
                        if (tempitem2.nodeType === 1 && tempitem2.nodeName === el.nodeName) { // If it is ELEMENT_NODE of the same name
                            pos += 1;
                        }
                        tempitem2 = tempitem2.previousSibling;
                    }

                    xpath = "*[name()='"+el.nodeName+"' and namespace-uri()='"+(el.namespaceURI===null?'':el.namespaceURI)+"']["+pos+']'+'/'+xpath;

                    el = el.parentNode;
                }
                xpath = '/*'+"[name()='"+xml.documentElement.nodeName+"' and namespace-uri()='"+(el.namespaceURI===null?'':el.namespaceURI)+"']"+'/'+xpath;
                xpath = xpath.replace(/\/$/, '');
                return xpath;
            }
        </script>
        <script>
            function context(event) {
                event.preventDefault();
                console.log(event.target);
                var sel_gen = new CssSelectorGenerator();
                var sel = sel_gen.getSelector(event.target);
                var xpath = getXPathForElement(event.target, document);
                alert("sel: " + sel + "; xpath: " + xpath);
            }
        </script>
    </head>

    <body>
        <div class=myclass>
            <div>
                <p oncontextmenu="context(event)">Right click me</p>
                <p>Clicking me won't help</p>
            </div>
        </div>
    </body>
</html>

此特殊情况警告:

  

sel: .myclass > div > :nth-child(1); xpath: /*[name()='HTML' and namespace-uri()='http://www.w3.org/1999/xhtml']/*[name()='BODY' and namespace-uri()='http://www.w3.org/1999/xhtml'][1]/*[name()='DIV' and namespace-uri()='http://www.w3.org/1999/xhtml'][1]/*[name()='DIV' and namespace-uri()='http://www.w3.org/1999/xhtml'][1]/*[name()='P' and namespace-uri()='http://www.w3.org/1999/xhtml'][1]

我相信图书馆能够比我相信自己更加正确!

然后尝试this jsfiddle

同样this jsfiddle修改Mozilla函数以提供更简单的xpath。

css选择器还有其他库可用,请参阅this answer to a similar question

答案 1 :(得分:3)

event.target - 表示您点击的元素