2017-03-09 17 views
0

基本上,我想要一个函数根据点击哪个单独操作多个元素。JS/jQuery - 我如何从一个元素ID的数字,并将其用作函数中的变量?

我有这些功能是做同样的事情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(); 
} 
}); 

正如你所看到的,我用这个功能全部结束在“1”工作的ID名称我为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)

我环顾四周,似乎无法想出办法做到这一点。

是否有其他方法可以做到这一点,比如将数字传递给函数?

回答

2

相反,只需修改您选择使用the "starts with" operator,而不是完全指定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? 
+0

感谢您的回复。这看起来像我所需要的。我确实需要价值,因为这些就像“多读”链接,所以我不希望所有的项目都扩大。我使用'$('。more')。'(function()'。类似于我想要做的事情,我会碰到一个类似于我想要做的事情的代码文件: – AdamDallas

+0

@AdamDallas:如果点击处理程序中的任何给定操作的目标都可以在DOM中相对于点击元素进行标识,您可能根本不需要解析该值。通常像'$(this).closest('some common parent element')这样的东西。发现('目标元素')'会做的伎俩。这取决于你,这将更容易维护。 – David

+0

@AdamDallas:究竟是一个更好的方法?您通常不希望在循环中创建*点击处理程序。你可以使用类来识别你的元素,这很好。但不要用循环来考虑这一点。只需使用选择器来识别您可点击的元素,然后使用单击处理程序来响应该事件。 – David

0

如果你能分享你的整个代码,这将有所帮助。从我的理解,应该是沿着这些路线的东西:

// 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(数量)。这就是为什么我要求整个代码通过创建多个函数来真正理解你的意思。

0

如果您知道变量名称的前缀,则后缀中包含您想要的数字。然后插入jQuery选择器。我之前做过,如果直接插入像$(YourNewVariableForID)不会工作,然后尝试$("#" + eval(YourNewVariableForID))

相关问题