在按钮上单击将div内部html指定为输入字段值

时间:2017-02-11 07:44:45

标签: javascript jquery html css

我想要的是当有人点击按钮时,将电话号码设置为输入值。该块是一个循环,其中显示不同的电子邮件和电话号码。如果在特定块中单击一次,则仅从该块获取电话号码。谢谢。

<div class="block">
     <div class="phone"><span>+1234567</span></div>
     <div class="email">
          <span>email@email.com</span>
          <button>CLick</button>
     </div>
</div>

<div class="block">
     <div class="phone"><span>+7696686</span></div>
     <div class="email">
          <span>another@email.com</span>
          <button>CLick</button>
     </div>
</div>

<div class="block">
     <div class="phone"><span>+897979877</span></div>
     <div class="email">
          <span>email2@email.com</span>
          <button>CLick</button>
     </div>
</div>
<input type="text" value="" id="phone">

这是我的代码:

jQuery(document).ready(function() {
    jQuery(".block button").click(function() {
        var contents = jQuery(this).find(".phone span").text();
        jQuery("#phone").val(contents);
    });
});

2 个答案:

答案 0 :(得分:1)

你标记了jQuery所以我假设你可以使用jQuery接收答案。尝试类似的事情:

$('button').click(function(){
   var phoneNumber = $(this).closest('.phone').find('span').text();
});

答案 1 :(得分:0)

Try this-

jQuery(document).ready(function($) {
   $(".block").each(function() {
        $(this).find('button').click(function(){
          var contents = $(this).parents('.block').find('.phone span').text();
          $("#phone").val(contents);
        });        
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="block">
     <div class="phone"><span>+1234567</span></div>
     <div class="email">
          <span>email@email.com</span>
          <button>CLick</button>
     </div>
</div>

<div class="block">
     <div class="phone"><span>+7696686</span></div>
     <div class="email">
          <span>another@email.com</span>
          <button>CLick</button>
     </div>
</div>

<div class="block">
     <div class="phone"><span>+897979877</span></div>
     <div class="email">
          <span>email2@email.com</span>
          <button>CLick</button>
     </div>
</div>
<input type="text" value="" id="phone">