获取SPAN标记的ID,并根据单击的标记向文本框字段添加一些值
当用户点击它时,我试图获取SPAN标记的ID。
由于每个标签的ID包含两位数字,因此它们将用于引用
到它们对应的隐藏文本框字段的值,
但我被困在这个问题上。
这是我编写的代码的一部分。
我需要你的帮助来完成它,因为我不知道如何继续前进。
$(document).ready(function(){ $("#^=content").click(function(event){ // var digit = extract the last two digit of the id var id_of_the_hidden_field = "hidden"+digit; $("#show").val()=$("#hidden").val(); }); }); Click to add the value Click to add the value
它看起来像这样:
$("[id^=content]").click(function(event){ $("#show").val($("#" + this.id.replace('content', 'hidden')).val()); });
你可以在这里测试一下 。 对此有一些更正,首先你需要一个属性starts-with selector ( [attr^=value]
)来按ID查找元素(尽管你可以给spans一个类并使用.class
)。 然后我们使用ID,通过string.replace()
将'content'
替换为'hidden'
,并通过该ID获取输入元素。 同样在设置值时使用.val(value)
.val() = value
无效:)
如果结构是一致的,你可以通过依赖在
旁边这样的事实来使这更简单:
$("[id^=content]").click(function(event){ $("#show").val($(this).next().val()); });
你不能在这里测试它
正如我在第一个例子中所说,如果在选项中添加分类,它将使您的生活更轻松,这是一个版本:
Click to add the value Click to add the value
和jQuery:
$(".clickable").click(function(event){ $("#show").val($(this).next().val()); });
这是演示中的那个版本
要么
var digit = $(this).attr(id).substring(7, 9);
Click to add the value Click to add the value
inheritance人: http : //jsfiddle.net/vNAEd/
这个适合你:
$("[id^=content]").click(function(){ $("#show").val($("#hidden"+this.id.substr(-2)).val()); });
这是代码的实际应用 。
你的选择器是错的。 请改用$("span[id^=content]")
$(document).ready(function(){ $("span[id^=content]").click(function(event){ var id = this.id; var digit = id.substring(id.length -2 , id.length); var id_of_the_hidden_field = "#hidden"+digit; $("#show").val( $( id_of_the_hidden_field ).val() ); }); });