点击上的Jquery附加功能不起作用。它会立即删除附加项目

时间:2017-09-13 04:14:57

标签: javascript jquery click append

我有两个选择标签。当我单击一个链接时,我希望所选的选项附加到另一个选项,但在它附加后立即删除它。这是我的代码。

<select id="senroll" multiple="multiple" name="esubject">

</select><br /><br />
<label for="lsubject">Subject List</label></br>
<select id="slist" multiple="multiple" name="lsubject">
  <?php foreach($slist as $subject): ?>
      <?php echo "<option value='" . $subject['s_id'] . "'>" .   
       $subject['sname'] . "</option>"; ?>
  <?php endforeach; ?>
</select><br /><br />   
<a href="" id="enroll">Enroll</a>
<a href="" id="drop">Remove</a>

这是我的jquery代码:

$(document).ready(function(){
        $('#enroll').on('click',  function(){

        var id = $('#slist').val();
        var snames = '#slist option[value="' + id + '"]';

        var sname = $(snames).text();
        var app = '<option value="' + id + '">' + sname + '</option>';
        $('#senroll').append(app);
        });
});

2 个答案:

答案 0 :(得分:0)

这样的东西?

JSFiddle Demo

$(document).ready(function(){
        $('#enroll').on('click',  function(){
        var id = $('#slist').val()[0];
        if(id){
            var snames = '#slist option[value="' + id + '"]';
          var sname = $(snames).text();
          var app = '<option value="' + id + '">' + sname + '</option>';
          $('#senroll').append(app);
        } 
        });
});

答案 1 :(得分:0)

&#13;
&#13;
$(document).ready(function() {
    $("#senroll").append($("<option></option>").val(1).html("One"));
    $("#senroll").append($("<option></option>").val(2).html("Two"));
    $("#senroll").append($("<option></option>").val(3).html("Three"));
    $('#senroll').on('click', function() {
        alert("I am clicked");
        var id = $('#slist').val()[0];
        var snames = '#slist option[value="' + id + '"]';
        console.log(id, snames);
        var sname = $(snames).text();
        console.log(sname);
        var app = '<option value="' + id + '">' + sname + '</option>';
        $('#enroll').append(app);
    });
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<select id="senroll" multiple="multiple" name="esubject">
</select><br /><br />
<label for="lsubject">Subject List</label></br>
<select id="slist" multiple="multiple" name="lsubject">
  <?php foreach($slist as $subject): ?>
      <?php echo "<option value='" . $subject['s_id'] . "'>" .   
       $subject['sname'] . "</option>"; ?>
  <?php endforeach; ?>
</select><br /><br />
&#13;
&#13;
&#13;

我不了解每个PHP的更多内容,但这可以在您的js代码中使用

希望这有帮助!