简体   繁体   English

我想用前置jQuery添加一个元素

[英]I want to add a element with prepend jQuery

I want to add a new a element when I click the button but it doesnt work 我想在单击按钮时添加一个新元素,但是它不起作用

<div id="add-container">
    <input type="text"> <button>add</button>
    <div id="megobrebi">
        <a>Levani</a>
        <a>Markozi</a>
        <a>Zuka</a>
        <a>Sandro</a>
    </div>
</div>
$(document).ready(function() {
    $('#add-container').on('click', 'button', function(){
        var value = $('#add-container input').val;
        var html = '<a>' + value + '</a>'
        $('$megobrebi').prepend(html);
    })
})

You have two errors in the handler for the click event on the button. 您在按钮上的click事件的处理程序中有两个错误。

First, you need to call the jQuery val method in order to get the value of the input. 首先,您需要调用jQuery val方法以获取输入的值。

Second, the selector for the DOM element where you want to prepend is not right. 其次,要在其前面添加DOM元素的选择器不正确。

Therefore, the code should be: 因此,代码应为:

$('#add-container').on('click', 'button', function(){
    var value = $('#add-container input').val();
    var html = '<a>' + value + '</a>'
    $('#megobrebi').prepend(html);
})

最后一行应该是

$('#megobrebi').prepend(html);

Change your script code to 将您的脚本代码更改为

$(document).ready(function() {
    $('#add-container button').on('click', function(e){
        e.preventDefault(); // You may use this line if you wish to disable the default functionality button.
        var value = $('#add-container input').val();
        var html = '<a>' + value + '</a>';
        $('#megobrebi').prepend(html);
    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM