jQuery只能点击元素数据

时间:2016-01-26 09:17:13

标签: javascript jquery click element

我希望有人可以帮我解决这个问题

我一直致力于创建按钮,点击它时会将数据添加到表单中 被送走了。

如下所示:

<div>
  <li id="song-button">
        <h3 class="song">Song #1</h3>
        <div class="artist">Artist #1</div>
  </li>

  <li id="song-button">
        <h3 class="song">Song #2</h3>
        <div class="artist">Artist #2</div>
  </li>  
</div>

  <form>
    <input type="hidden" name="title" value="">
    <table width="100%" border="0">
      <tbody>
        <tr>
          <td align="left">
            <label>Artist: </label>
          </td>
            ................

脚本代码:

$( "#song-button" ).click(function() {

    var artist = $(".artist").text();
    var song = $("h3").text();

    $("#artist-field").val(artist);
    $("#song-field").val(song);
});

无论如何只能点击 li 点击该表单的数据?

3 个答案:

答案 0 :(得分:2)

id对每个元素都应该是唯一的。使用song-button class代替id,如下所示。

<div>
    <li class="song-button">
        <h3 class="song">Song #1</h3>
        <div class="artist">Artist #1</div>
    </li>
    <li class="song-button">
        <h3 class="song">Song #2</h3>
        <div class="artist">Artist #2</div>
    </li>  
</div>

使用find获取点击元素下的数据。

$( ".song-button" ).click(function() {
    var artist = $(this).find(".artist").text();
    var song = $(this).find("h3").text();

    $("#artist-field").val(artist);
    $("#song-field").val(song);
});

答案 1 :(得分:1)

你必须用class更改你的选择器,id是唯一的,所以我已经改变了你的代码......

<div>
  <li class="song-button">
        <h3 class="song">Song #1</h3>
        <div class="artist">Artist #1</div>
  </li>

  <li class="song-button">
        <h3 class="song">Song #2</h3>
        <div class="artist">Artist #2</div>
  </li>  
</div>

  <form>
    <input type="hidden" name="title" value="">
    <table width="100%" border="0">
      <tbody>
        <tr>
          <td align="left">
            <label>Artist: </label>
          </td>
        </tr>
      </tbody>
   </table>
  </form>

并且脚本必须像这样更改

$( ".song-button" ).click(function() {

var artist = $(this).find('.artist').text();
var song = $(this).find('.song').text();

$("tbody tr").append('<td align="left"><label>Artist:'+artist+' </label></td>');
});

答案 2 :(得分:0)

ID必须是唯一的。所以我编辑了歌曲按钮&#39;作为班级               

    $(document).ready(function () {

        $(".song-button").click(function () {

            var artist = $(this).find('div.artist').text()
            var song = $(this).find('h3.song').text()

            alert(artist)
            alert(song)
        });


    });
</script>
</head>

<body>
    song-button
    <div>
  <li class="song-button">
        <h3 class="song">Song #1</h3>
        <div class="artist">Artist #1</div>
  </li>

  <li class="song-button">
        <h3 class="song">Song #2</h3>
        <div class="artist">Artist #2</div>
  </li>  
</div>

</body>

</html>