簡體   English   中英

JS / jQuery-如何獲取元素ID中的數字並將其用作函數中的變量?

[英]JS/jQuery - How can I a number from an element ID and use it as a variable in functions?

基本上,我希望一個函數根據單擊哪個而分別作用於多個元素。

我有3個功能執行相同的操作:

$("#morelink1, #pic1").click(function() {
var imgHeight = $(".pic").height();
var image = $('#more1').parent('.content').siblings(
  '.image');
if ($('#more1').is(":visible")) {
  $("#more1").slideUp(200, "linear");
  image.height(contHeight);
  showtext1();
  $("#closemore1").hide();
} else {
  $("#more1").slideDown(200, "linear");
  image.height(imgHeight);
  hidebutton1();
  hidetext1();
}
 });

如您所見,我在此函數中使用的ID的名稱都以“ 1”結尾。 我將此功能復制了2和3。

除了復制外,還必須有一種方法從#morelink1提取數字,使其成為變量,然后將該數字附加到函數中的ID上。

我想要類似的東西:

var NUMBER = [get the number from the ID of the element that was clicked];

$("#morelink + NUMBER, #pic + NUMBER").click(function() {

我也有內置於此函數中的函數showtext1()hidebutton1()hidetext1() 那些也被復制,只是數字改變了。 我希望能夠使用此功能中的功能執行相同的操作。 會像showtext(NUMBER)嗎?

我環顧四周,似乎無法找出解決方法。

還有其他方法,例如將數字傳遞給函數嗎?

相反,只需修改選擇器以使用“開頭為”運算符即可,而不是完全指定id

$("[id^='morelink'], [id^='pic']").click(function() {

這將匹配id值以'morelink''pic'開頭的每個元素,無論id的其余部分是什么。

如果您仍需要點擊處理程序中的該值,則可以從當前元素的id解析它。

var idString = $(this).attr('id');
// use whatever logic you define to parse the number value.
// for example, maybe a regular expression which matches only numeric characters?

如果您可以共享整個代碼,那將會有所幫助。 據我了解,應該遵循以下原則:

// Append click event to elements whose id starts with morelink or pic.
$('[id^="morelink"], id^=["pic"]').click(function() {
  // Get id of current clicked element.
  var id = $(this).attr('id');
  // Use RegExp to extract number.
  var number = id.match(/[\d]+/)[0];

  // Your functions starting.
  var imgHeight = $(".pic").height(); //should this be pic + NUMBER?
  var image = $('#more' + number).parent('.content').siblings('.image');

  if ($('#more' + number).is(":visible")) {
    $('#more' + number).slideUp(200, "linear");
    image.height(contHeight);
    // Executes selectMore1(); if number = 1
    window['showtext' + number]();
   $("#closemore" + number).hide();
  } else {
    $("#more" + number).slideDown(200, "linear");
    image.height(imgHeight);
    // Executes hidebutton1(); if number = 1
    window['hidebutton' + number]();
    // Executes hidetext1(); if number = 1
    window['hidetext' + number]();
  }
});

但是,我不認為hidebutton1()應該存在,而是hidebutton(number)。 這就是為什么我要求整個代碼真正了解您當前創建多個函數的含義。

如果您知道變量名的前綴,請在所需的數字后綴。 然后插入jQuery選擇器。 我之前已經做過,如果像$(YourNewVariableForID)這樣的直接插入無法正常工作,請嘗試$("#" + eval(YourNewVariableForID))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM