【问题标题】:Jquery get unique css selector on rightclick menu item or click a dom elementJquery 在右键单击菜单项或单击 dom 元素上获取唯一的 css 选择器
【发布时间】:2017-10-29 08:10:16
【问题描述】:

我试图在右键单击 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);
});

【问题讨论】:

  • 你签出this answer了吗?
  • 单击和右键单击与 $(this) 的工作方式不同,并为 xpath 或 css 选择器拉取其父元素。

标签: javascript jquery xpath css-selectors


【解决方案1】:

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

【讨论】:

  • 获取当前 html 元素的好指针。请问有什么选项可以获得独特的 CSS 选择器吗?
  • 我会动态添加一个唯一的ID,例如:var unique = 'id' + (new Date ()). GetTime (); $(event.target).attr('id', unique);
  • 我的意思是如果有 4 个具有相同名称的类,我想为单击的元素获取正确的 css 选择器。任何指针来获取单击元素的 css 选择器?
【解决方案2】:

@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 &gt; div &gt; :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

【讨论】:

  • 这个库可以免费使用吗?在 git hub 中它说未经许可。
  • 它通过UNLICENSE license 获得许可,上面写着“这是发布到公共领域的免费且不受阻碍的软件。”所以是的,它可以免费使用。
  • 不,因为显然 xpath 不会包含例如元素的 id 或类。但通常在编写 HTML / javascript / CSS 时,您只真正关心选择器,而 xpath 并不是很有用。你真的需要一个 xpath 来做某事,还是只需要一个 CSS 选择器?
  • 用 xpath 和 jsfiddle 更新了我的答案。
  • 它是一个同样有效的 xpath,完全没有歧义并且带有命名空间信息。如果需要,可以轻松修改函数以提供更简单的路径,请参阅jsfiddle.net/daphtdazz/8jgyxrbt
猜你喜欢
  • 2012-11-26
  • 1970-01-01
  • 2016-03-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多