简体   繁体   中英

javascript: Replacing button with a href

So i have this html/javscript code:

<script type="text/javascript" src="includes/jquery/jquery.js"></script>
<button type="button">Click Me</button>
<p></p>
<?php $linkas= $_GET["linkas"]; ?>
<script type="text/javascript">
$(document).ready(function(){
    $("button").click(function(){

        $.ajax({
            type: 'POST',
            url: 'getmovies.php?linkas=<?php echo $linkas; ?>',
            success: function(data) {
                document.write(data);
    document.close();
            }
        });
});
});
</script>

How can i replace the button with text? i'v tried to replace the button.click with a a.click function but it still does not work. Thanks.

I am not entirely sure if I understood what you are asking. But as far as I understood you want to switch the button element with an a element.

This can be done like that:

$(document).ready(function(){
    $("button").click(function(){
        var href = "http://example.com"
        var content = $(this).text();
        $("button").replaceWith("<a href=\"" + href + "\">" + content + "</a>");
    });
    //... Your Code ...
});

Demo:

 $(document).ready(function(){ $("button").click(function(){ var href = "http://example.com" var content = $(this).text(); $("button").replaceWith("<a href=\\"" + href + "\\">" + content + "</a>"); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button type="button">Click Me</button> 

Replace your <button/> with <a></a> and bind click event to element. Check this fiddle

Try this

<script type="text/javascript" src="includes/jquery/jquery.js"></script>
<a href="#" id="my-link">Click Me</a>
<p></p>
<?php $linkas= $_GET["linkas"]; ?>
<script type="text/javascript">
$(document).ready(function(){
    $("#my-link").click(function(evt){
        evt.preventDefault();
        $.ajax({
            type: 'POST',
            url: 'getmovies.php?linkas=<?php echo $linkas; ?>',
            success: function(data) {
                document.write(data);
    document.close();
            }
        });
});
});
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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