基本上,我希望一个函数根据单击的元素单独作用于多个元素。
我有 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)
的东西吗?
我环顾四周,似乎无法找到一种方法来做到这一点。
还有其他方法可以做到这一点,例如将数字传递给函数吗?
最佳答案
相反,只需修改您的选择器以使用 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?
关于javascript - JS/jQuery - 如何从元素 ID 中获取数字并将其用作函数中的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42698497/