jquery - 获取 SPAN 标签的 ID,并根据单击的标签向文本框字段添加一些值

标签 jquery

当用户单击 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());
});​

You cant test it here

<小时/>

正如我在第一个示例中所说,如果在选项中添加类,它将使您的生活更轻松,这是一个这样做的版本:

<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());
});​

Here's that version in a demo

关于jquery - 获取 SPAN 标签的 ID,并根据单击的标签向文本框字段添加一些值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3223446/

相关文章:

php - jQuery ajax 调用在 Mac Safari 和 Chrome 浏览器上返回空错误

javascript - 大型 sql 表 - 选择所有但使用 javascript/PHP 逐步显示

jquery - Fancy Box - 关闭 iframe 弹出窗口时如何刷新父页面?

javascript - 替换每第 n 个类名并借助 jQuery 替换它

php - jQuery.ajax 文件删除

发布 jQuery 时 JavaScript 数组被编码

javascript - 将触摸屏设备的 ('hover' ) 更改为 ('click' )?

javascript - AngularJS:当 css 类发生变化时如何通过切换更改颜色属性?

ajax - 当使用 JSON/AJAX 时,这些数据到底发送到哪里以及如何访问它?

java - Ajax查询中Java + Spring的CORS政策错误