JS - Dynamic Href Change

2019-09-02 09:37发布

Ive tried many way but im new to JS, I mainly do PHP.

Anyway the code:

    <script>
        var userinput = $('input[name="imdbid"]');

        userinput.change(

        function(){
            $('#userimdb').attr('href')+$('input[name="imdbid"]').val();
        }

        );
</script>

Basically, the imdbid is gotten from a input tag, basically I want to append whatever the user types to a href of a tag, This doesnt seem to work doe. When I alert() it, it seems to give me the output of what its meant to but when I remove alert() it doesnt seem to change the href, I also tried .setAttribute() but that also just did nothing.

Please help me out im going insane right now.

2条回答
老娘就宠你
2楼-- · 2019-09-02 10:01

You're not setting the attribute right now, only accessing it. In addition, you need to store the original href attribute somewhere so you're not adding the same text repeatedly. Here's the updated code:

var userinput = $('input[name="imdbid"]');
var orighref = $('#userimdb').attr('href');
userinput.change(function(){
    $('#userimdb').attr('href', orighref + userinput.val());
});
查看更多
在下西门庆
3楼-- · 2019-09-02 10:01

Try this:

You need to assign it to href attribute..

var userimdb=$('#userimdb');
var baseURL=userimdb.attr('href');
$('input[name="imdbid"]').change(function()
{
    var userimdb=$('#userimdb');
    userimdb.attr('href', baseURL + $(this).val());
});
查看更多
登录 后发表回答