jQuery&变量ID名称 [英] Jquery & Variable ID Names

查看:91
本文介绍了jQuery&变量ID名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图避免为不同的ID使用相同的代码.诸如Submitter1,submitter2等之类的东西.在同一过程中,让该变量还用于获取differentlocation1,differentlocation2等的输入框ID.有人可以帮我解决下面的代码吗?

I am trying to avoid having the same code for different ids. Something like submitter1, submitter2, etc. In the same process, having the variable also used to get the input box id of differentlocation1, differentlocation2, etc. Can someone help me out with the code below?

$(document).ready(function() {

    $('#submitter<--Variable Here-->').click(function(event) {
        event.preventDefault();
        var newlocation = $("input[name=differentlocation"<--Same Variable Here-->"']");
        alert(newlocation); //testing purposes
        //$('#location').val(newlocation).change(); //Changes location input box
        //$("#submit").click(); //submits new location

    });
});

此代码使用静态ID进行工作,但是就像我说的那样,我也希望将其调整为使用可变ID.

This code works using static ids, but like I said I would like to adjust it to use variable ids as well.

谢谢.

推荐答案

您可以使用 属性始于选择器:

You can use the attribute starts with selector:

$('button[id^="submitter"]').click(...);

click函数中,您可以使用简单的字符串方法获取id:

Inside the click function, you can get the id using simple string methods:

var uuid = this.id.slice(9),
    newlocation = $('input[name="differentlocation'+uuid+'"]');

正在运行的演示: http://jsfiddle.net/wy8X9/

这篇关于jQuery&amp;变量ID名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆