2011-10-31 46 views
1

我想避免为不同的ID具有相同的代码。就像submitter1,submitter2等。在同一个过程中,让变量也用来获取不同地点1,不同地点2的输入框ID。有人可以帮我解决下面的代码吗?JQuery和可变ID名称

$(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以及。

谢谢。

+1

为什么不能使用类名将元素与共享行为关联? –

回答

4

可以使用attribute starts with selector

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

里面的click功能,你可以得到id使用简单的字符串方法:

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

工作演示:http://jsfiddle.net/wy8X9/

+0

@ Andy E这样看起来是否正确:'$('button [id^='submitter']')。click(function(event)'这个id提交者是一个按钮 – Go3Team

+0

@ Go3Team:是的,看起来是正确的 –

+0

我也有'var uuid = this.id.slice(9); alert(uuid);'它不会提示任何建议? – Go3Team

1

的自从multip以来,正确的解决方案是使用类而不是ID le元素可以具有相同的类。为了引用具有相同可变部分的输入,可以使用该ID的一部分或甚至更好的数据字段(在HTML中为data-whatever="...",在JS中为$(elem).data('whatever')

1

将ID设置为data-id并指向它们像这样

<tag class="submitter" data-id="n"> 

$('.submitter').click(function(){ 
    id = $(this).attr('data-id'); 
var newlocation = $("input[name=differentlocation"+id+"']"); 
}) 
+0

其中“n”是一个数字。 –

+0

我使用隐藏的输入类型,所以我有:'var newlocation = $(“hidden [name = differentlocation”+ id +“']” );'如果我做'alert(newlocation);'警告窗口说'object Object' - 任何想法? – Go3Team

+0

$(“hidden [name = differentlocation”+ id +“'”“”)。val() –

1

当你想分享一些东西时,我建议你甚至根据一个普通的类名来关联它。

您可以阅读this.id以获取事件目标的ID并在其中进行操作。

$('.submitter').click(function(e) { 
    e.preventDefault(); 
    var numId = this.id.replace(/[^0-9]+/, ''), 
     newlocationId = "input[name=differentlocation" + numId+ "']"; 

    alert(newlocationId); 
}); 

实施例:http://jsfiddle.net/qud32/

或者,也可以使用选择 “属性开头” 安迪暗示。