当用户单击 SPAN 标记时,我试图获取该标记的 ID。
由于每个标签的ID包含两位数字,因此它们将用于引用
为其相应隐藏文本框字段的值,
但我对这个问题很困惑。
这是我编写的部分代码。
我需要你的帮助来完成它,因为我不知道如何继续。
<script type="text/javascript">
$(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();
});
});
</script>
<div id="test22">
<span id="content22">Click to add the value</span>
<input type="hidden" id="hidden22" value="hello">
</div>
<div id="test33">
<span id="content33">Click to add the value</span>
<input type="hidden" id="hidden33" value="world">
</div>
<input type="text" id="show">
最佳答案
它看起来像这样:
$("[id^=content]").click(function(event){
$("#show").val($("#" + this.id.replace('content', 'hidden')).val());
});
You can test it here 。对此有一些更正,首先您需要一个 attribute starts-with selector ( [attr^=value]
) 通过 ID 查找元素(尽管您可以为跨度指定一个类并也使用 .class
)。然后我们使用 ID,替换 'content'
与 'hidden'
通过 string.replace()
并通过该 ID 抓取输入元素。另外,在设置值时,请使用 .val(value)
, .val() = value
无效:)
如果结构一致,您可以使这变得更简单,因为 <input type="hidden" />
就在<span>
旁边像这样:
$("[id^=content]").click(function(event){
$("#show").val($(this).next().val());
});
<小时/>
正如我在第一个示例中所说,如果在选项中添加类,它将使您的生活更轻松,这是一个这样做的版本:
<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());
});
关于jquery - 获取 SPAN 标签的 ID,并根据单击的标签向文本框字段添加一些值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3223446/