jQuery尝试访问span中的文本

时间:2015-06-07 04:08:26

标签: javascript jquery html dom

<ul class="info">                        
  <li data-edit="string">
    <span class="content">
      Sing Sing
    </span>
    <div class="edit-panel">
      <button data-action="delete">Delete</button>
      <button data-action="edit">Edit</button>
    </div>
  </li>
</ul>

点击删除按钮后,如何在此处访问Sing Sing?这就是我正在尝试的......

$(selector).each(function(){
  var $mainElement = $(this);    
  $mainElement.find("[data-action=delete]").off().on("click", function(){           
    var sing = $(this).parents("[data-edit]").find("#gogo").text($(this).val());             
  });
});

2 个答案:

答案 0 :(得分:1)

<!DOCTYPE html>

<head>
  <meta charset="utf-8">
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
  <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
  <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">

  <style>
  </style>
</head>
<body>
  <ul class="info">                        
  <li data-edit="string">
  <span class="content">
  Sing Sing
  </span>
  <div class="edit-panel">
          <button data-action="delete">Delete</button>
          <button data-action="edit">Edit</button>
      </div>
  </li>
  </ul>
<script>
 $(document).ready(function(){
   console.log($(".content").text());
  });
</script>

</body>
</html>

答案 1 :(得分:0)

我只会将selector替换为".edit-panel",因为这是按钮所在的div。

从内容中获取文本,而不是试图遍历jquery树直接点击它,也就是替换

var sing = $(this).parents("[data-edit]").find("#gogo").text($(this).val());

var sing = $(".content").text().trim();