JS - Dynamic Href Change

2019-09-02 09:15发布

问题:

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.

回答1:

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());
});


回答2:

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());
});