select.prev(“。class”)。val();返回未定义的值

时间:2019-04-22 17:38:28

标签: javascript jquery html

我正在尝试返回链接到html页面中的类的值。它不返回声明的值,而是返回未定义的值。我添加了console.log来显示我正在输出的内容,并且状态未定义。

$(document).on("change", "select.playlist", function() {
  var select = $(this);
  var songId = select.prev(".songId").val();
  var playlistId = select.val();
  //selects dropdown menu thats currently selected
  console.log("playlistId: " + playlistId);
  console.log("songId: " + songId);
});

function showOptions(button) {
  var songId = $(button).prevAll(".songId").val();
  var menu = $(".optionsMenu");

  var menuWidth = menu.width();
  menu.find(".songId").val(songId);

  var scrollTop = $(window).scrollTop();

  var elementOffset = $(button).offset().top;

  var top = elementOffset - scrollTop;

  var right = $(button).position().right;

  menu.css({
    "top": top + 8 + "px",
    "right": +menuWidth - 100 + "px",
    "display": "inline"
  });
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='songOptions'>
  <input type='hidden' class='songId' value='" . $albumTrack->getId() . "'>
  <img class='optionsButton' onclick='showOptions(this)' src='assets/images/icons/more.png'>
</div>

console.log()应该输出与您检查元素时看到的值匹配的值。

1 个答案:

答案 0 :(得分:0)

您遇到的问题实际上是因为当您像在onclick中一样调用this时,会得到标签的HTML而不是对象本身。我删除了onclick并将其更改为click事件监听器,并且可以正常工作。

$(document).on("change", "select.playlist", function() {
  var select = $(this);
  var songId = select.prev(".songId").val();
  var playlistId = select.val();
  //selects dropdown menu thats currently selected
  console.log("playlistId: " + playlistId);
  console.log("songId: " + songId);
});



$(document).on("click",".optionsButton",function(){
  var songId = $(this).prevAll(".songId").val();
  console.log(songId);
  var menu = $(".optionsMenu");

  var menuWidth = menu.width();
  menu.find(".songId").val(songId);

  var scrollTop = $(window).scrollTop();

  var elementOffset = $(this).offset().top;

  var top = elementOffset - scrollTop;

  var right = $(this).position().right;

  menu.css({
    "top": top + 8 + "px",
    "right": +menuWidth - 100 + "px",
    "display": "inline"
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='songOptions'>
  <input type='hidden' class='songId' value='" . $albumTrack->getId() . "'>
  <img class='optionsButton' src='assets/images/icons/more.png'>
</div>