如何通过单击按钮而不是在页面加载之前加载div的内容?

你好,我之前问过如何通过单击按钮而不是在页面加载之前加载div的内容(URL),我得到了以下代码作为答案:

<script type="text/javascript">
    function toggleDiv(id){
        if ($('#' + id).html() == '') {
            $.ajax({
                url: 'api.microsofttranslator.com/V2/Ajax.svc/Translate?appId=SOMETHING&from=en&to=de&text=Hello', // your url to microsoft translator
                success: function(data) {
                    $('#' + id).html(data);
                },
                error: function() {
                    $('#' + id).html('The resource could not be loaded');
                }
            });
        }

        $('#' + id).toggle(); // Toggle div visibility
    }
</script>

<a href="#" onclick="toggleDiv('a')">Show/Hide Value</a>
<div id="a" style="display:none"></div>

但我试过后发现,如果你放置txt链接(例如(http://knowpersia.com/a.txt)),它将无法正常工作,并且始终显示“无法加载资源”。

其次,“显示/隐藏值”链接使用href =#和onclick系统才能起作用。当我在网站上使用它时,单击它会返回到主页。有没有办法将其更改为:

<a href="javascript:toggleDiv('a')">Show/Hide Value</a>

谢谢!

You have to pass an id to the toggleDiv() function, and you're passing a collection of objects -> toggleDiv('a') // Nop. Also, if you're using jQuery, I suggest you get rid of that ugly inline code. Then, you can pass jQuery objects into your function:

<a href="#" id="link">Show/Hide Value</a>
<div id="content"></div>

.

var toggleDiv = function($el) {
    if ($el.empty()) { // You can just use `empty()`
        $.ajax({
            url : 'api.microsofttranslator.com/V2/Ajax.svc/Translate?appId=SOMETHING&from=en&to=de&text=Hello', // your url to microsoft translator
            success : function (data) {
                $el.html(data);
            },
            error : function () {
                $el.html('The resource could not be loaded');
            }
        });
    }
    $el.toggle(); // Toggle div visibility
};

$('#link').click(function(){ toggleDiv($('#content')); });