jQuery从单选按钮追加到div

时间:2018-10-28 19:23:01

标签: jquery html append

当用户双击图像时,我想附加到附近的div(imageSelection),文件名或alt属性值。现在,当我双击图像时,什么也没有发生,所以我认为我的代码有误,但不确定在哪里。

    $(document).on('dblclick', 'img', function () {
      var imgurl = window.location.pathname + $(this).attr('src');
      window.open(imgurl, '_blank');
    });
    
    $("input[name=imageselect]:radio").click(function () {
      var imgurl = window.location.pathname + $(this).attr('src');
      var $imageSelection = $('#image_selection');
      
      if ($('input[name=imageselect]:checked').val() == "filename") {
        var varsrc = $(this).attr('src');
        $imageSelection.append(varscrc);
      } else {
        var varalt = $(this).attr('alt');
        $imageSelection.append(varalt);
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="radio_images">
    File Name   <input type="radio" name="imageselect" value="filename">	<br>
    Description  <input type="radio" name="imageselect" value="description" checked> 	<br>
    </div>
    
    <div id ="imageSelection">
    </div>
    
    <div id="images">
    <h3>Some Images</h3>
    	<p><img src="firetruck.jpg" alt="pic of truck">  |
    	<img src="baseball.jpg" alt="pic of baseball" >  |
    	<img src="soccer_ball.jpg" alt="pic of soccer ball" >
    	</p>
    </div>

1 个答案:

答案 0 :(得分:0)

好吧,所以您的imageSelection ID中有一个错字,您需要更改.click函数,以便单击图像而不是单选输入时会发生追加。您可以在以下代码段中找到更改。

$(document).on('dblclick', 'img', function () {
  var imgurl = window.location.pathname + $(this).attr('src');
  window.open(imgurl, '_blank');
});

$("img").click(function () {
  var imgurl = window.location.pathname + $(this).attr('src');
  var imageSelection = $('#imageSelection');

  if ($('input[name=imageselect]:checked').val() === "filename") {
    var varsrc = $(this).attr('src');
    imageSelection.append(varsrc);
  } else {
    var varalt = $(this).attr('alt');
    imageSelection.append(varalt);
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="radio_images">
File Name   <input type="radio" name="imageselect" value="filename">    <br>
Description  <input type="radio" name="imageselect" value="description" checked>    <br>
</div>

<div id ="imageSelection">
</div>

<div id="images">
<h3>Some Images</h3>
    <p><img src="firetruck.jpg" alt="pic of truck">  |
    <img src="baseball.jpg" alt="pic of baseball" >  |
    <img src="soccer_ball.jpg" alt="pic of soccer ball" >
    </p>
</div>

希望有帮助。