AJAX console.log返回未定义

时间:2018-12-07 22:45:28

标签: javascript ajax undefined console.log

我的数据库的while循环中有以下两个输入字段:

<input type="button" class="button" name="cartbtn" id="button<? 
=$product['id'];?>"  value="Quick Add-to-Cart">

这是触发AJAX的按钮:

<script type="text/javascript">

$(document).ready(function(data){

    $('.button').click(function(){

        var product_id = $(this).attr('id');
        var product_name = $('#name'+product_id).val();
        console.log(product_name);

    });
});

</script>

这样做会引起我的问​​题:

console.log(product_name);

var product_id = $(this).attr('id');返回为未定义。

如果我console.log(product_id)返回SELECT *, ROW_NUMBER()OVER(PARTITION BY T.CLIENT_ID, T.SITE_NUM ORDER BY T.START_DATE, T.RECORD_ID) FROM #TEMP T LEFT JOIN #TEMP T2 ON T2.CLIENT_ID = T.CLIENT_ID AND T2.RECORD_ID = T.RECORD_ID - 1 ORDER BY T.RECORD_ID WHERE T.SITE_NUM <> T2.SITE_NUM OR T2.SITE_NUM IS NULL 没问题,例如:(应如此)返回“ button6”。

2 个答案:

答案 0 :(得分:2)

如果console.log(product_id)返回button6,则表明您的product_namenamebutton6。我相信您希望它成为name6

由于您过于复杂,所以最简单的方法是:

var product_name = $(`#name${product_id.slice(6)}`).val();

您使用slice(6)方法删除'button'的前六个字符。

答案 1 :(得分:1)

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8" />
  <link rel="stylesheet" href="https://netdna.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" />
  <link href="bootstrap-suggest.css" rel="stylesheet" type="text/css" />
</head>

<body>
  <textarea class="form-control" rows="8" id="example-1">type after ->  @</textarea>

  <script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
  <script src="http://lodev09.github.io/bootstrap-suggest/bower_components/bootstrap-suggest/bootstrap-suggest.js"></script>
  <script>
    $('#example-1').suggest('@', {
      data: function(q) {
        if (q) {
          return $.getJSON('https://api.myjson.com/bins/18vsxq', {
            q: q
          }).then(function(Response) {
            return Response.users
          });
        }
      },
      map: function(user) {
        return {
          value: user.username,
          text: '<strong>' + user.username + '</strong> <small>' + user.fullname + '</small>'
        }
      }
    })
  </script>
</body>

</html>

它前面不应有“按钮”,所以:

id="button<?=$product['id'];?>"

是正确的。我忘了,抱歉。