它看起来像这样:
$("[id^=content]").click(function(event){
$("#show").val($("#" + this.id.replace('content', 'hidden')).val());
});
你可以在这里测试一下 http://jsfiddle.net/6TCvq/。对此有一些更正,首先你需要一个属性以选择器开头 http://api.jquery.com/attribute-starts-with-selector/ ([attr^=value] http://api.jquery.com/attribute-starts-with-selector/)通过 ID 查找元素(尽管您可以为跨度指定一个类并使用.class
以及)。然后我们使用 ID,替换'content'
with 'hidden'
via string.replace() http://www.w3schools.com/jsref/jsref_replace.asp并通过 IS 抓取输入元素。设置值时也使用.val(value) http://api.jquery.com/val/, .val() = value
无效:)
如果结构是一致的,你可以使这变得更简单,因为<input type="hidden" />
旁边是<span>
像这样:
$("[id^=content]").click(function(event){
$("#show").val($(this).next().val());
});
你不能在这里测试它 http://jsfiddle.net/6TCvq/1/
正如我在第一个示例中所说,在选项中添加类将使您的生活更轻松,这是一个这样做的版本:
<div id="test22">
<span id="content22" class="clickable">Click to add the value</span>
<input type="hidden" id="hidden22" value="hello">
</div>
<div id="test33">
<span id="content33" class="clickable">Click to add the value</span>
<input type="hidden" id="hidden33" value="world">
</div>
<input type="text" id="show">
和 jQuery:
$(".clickable").click(function(event){
$("#show").val($(this).next().val());
});
这是演示中的版本 http://jsfiddle.net/6TCvq/2/