$(this)不能与javascript创建的元素一起使用?

时间:2016-06-30 15:55:17

标签: javascript jquery

我无法找出为什么我的脚本无法正常工作。这是一个简单的表格:

<table>
  <tr>
    <th>Name</th>
    <td>Paul Stevenson</td>
  </tr>
    <tr>
    <th>Date</th>
    <td>28. 09. 1978</td>
  </tr>
</table>

我的脚本添加了指向元素的链接。

var toolbar = $("<div />");
var link = $("<a />").attr({"target" : "_blank"});
toolbar.append( gmaps );

当用户将光标移动到第th个元素时,它会显示工具栏。

$('th').on("mouseenter mouseleave", function(e) {
      if (e.type === 'mouseenter') { $(this).append( toolbar ); }
      else { $(this).find( $("div") ).remove() }
  });

为什么我的变量

var thisNext = $(this).parent().next().text();

没有获取td文本而不将其添加到链接?

您也可以看到codepen

2 个答案:

答案 0 :(得分:2)

当你在函数

中执行$(this)时
$('th').on("mouseenter mouseleave", function(e) {

然后$(this)指向 th 元素但是当你访问$(this)来获取文本时

var thisNext = $(this).parent().next().text();

它在函数之外,这里$(this)指向窗口对象。

如果您需要在此处使用正确的选择器选择文本。点击此处http://www.w3schools.com/jquery/jquery_selectors.asp

这是您尝试实现的更新代码。

$('th').on("mouseenter mouseleave", function(e) {

  if (e.type === 'mouseenter') { 

    var toolbar = $("<div />").css({
      "padding": "5px",
      "background" : "#F8F8F8",
      "position" : "absolute",
      "borderRadius" : "5px 0 5px 5px",
      "left" : "-30px",
      "top" : "0",
      "zIndex" : "99"
    });

    var link = $("<a />").css({
        "display" : "block",
        "height" : "20px",
        "width" : "20px",
        "marginBottom" : "5px",
        "background-size" : "100%",
        "position" : "relative"}).attr({
          "target" : "_blank"
    });
    var thisNext = $($(this).parent().children('td')[0]).text();
    var gmaps = link.clone().css({"background" : "red"}).attr({
        href: 'https://www.google.cz/search?q=' + thisNext });
    toolbar.append( gmaps );
    $(this).append( toolbar ); }
    else 
    { 
      $(this).children('div').remove();
    }
  });

codepen:http://codepen.io/deep2701/pen/YWVkkA?editors=0010#anon-signup

希望这会对你有所帮助。

答案 1 :(得分:1)

您尝试在处理程序之外使用this - 因此this未设置为您认为的内容。内部$('th').on("mouseenter mouseleave", function(e) { this指的是th被采取行动 - 在您的示例中,您只是尝试访问this并假设它指的是您想要的内容。