基本上,我想要一个函数分别作用于多个元素,这取决于哪个元素被单击。
我有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();
}
});
如您所见,我在此函数中使用的in的名称都以“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)
一样吗?
我环顾四周,似乎想不出一种方法来做这件事。
有没有其他方法可以做到这一点,比如向函数传递一个数字?
发布于 2017-03-09 14:58:49
相反,只需修改选择器以使用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?
发布于 2017-03-09 15:07:35
如果你能分享你的全部代码,那会很有帮助。根据我的理解,它应该是这样的:
// 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)。这就是为什么我要求完整的代码来真正理解你现在创建多个函数是什么意思。
发布于 2017-03-09 15:30:30
如果您知道变量名称的前缀,请使用所需的数字作为后缀。然后插入jQuery选择器。我以前也这样做过,如果像$(YourNewVariableForID)
这样的直接插件不起作用,那就试试$("#" + eval(YourNewVariableForID))
。
https://stackoverflow.com/questions/42698497
复制相似问题