【发布时间】: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