简体   繁体   English

使用onclick输入运行HTML代码的HTML

[英]HTML using onclick input to run javascript code

I am currently trying to implement a menu with many clickable buttons - appetizers, soups, etc. By using parameters, I can send the type of food to my JavaScript. 我目前正在尝试实现带有许多可单击按钮的菜单-开胃菜,汤等。通过使用参数,我可以将食物类型发送到JavaScript。
These are the buttons. 这些是按钮。
http://puu.sh/kugEs/5048221343.jpg http://puu.sh/kugEs/5048221343.jpg

This is the code when I click on appetizers. 这是我单击开胃菜时的代码。

function scroll(type) {
    var test = "('#" + type + "')";
    alert(test); //('#appetizers')

    $("html, body").animate({ scrollTop: $test.offset().top-150 }, 600); //this doesnt work
    $("html, body").animate({ scrollTop: $('#appetizers').offset().top-150 }, 600); //this works
}

Of course I want to make it so that I don't have to manually use the working line. 当然,我想这样做,这样就不必手动使用工作线。 I want to use the one that doesn't work that it can be applied to all buttons running the same function with only different parameters. 我想使用一个不起作用的按钮,它可以应用于仅使用不同参数即可运行相同功能的所有按钮。

How can I use the var test in order to run the line that doesn't work? 我如何使用var测试来运行无效的行?

You should use $ and take care about your quotes:: 您应该使用$并注意报价::

var $test = $('#' + type);  // Now it's a jQuery Object

In your example: 在您的示例中:

function scroll(type) {
    var $test = $('#' + type);
    $("html, body").animate({ scrollTop: $test.offset().top-150 }, 600);
}

You should define $test as an object, instead of a string. 您应该将$ test定义为对象,而不是字符串。

function scroll(type) {
    var test = $('#' + type);
    alert($test.attr("id")); // appetizers
    $("html, body").animate({ scrollTop: $test.offset().top-150 }, 600);
}

Try it with this code. 尝试使用此代码。 It should work. 它应该工作。

function scroll(type) {
    var test = "('#" + type + "')";      
    alert(test); //('#appetizers')
    $("html, body").animate({ scrollTop: $('#'+type).offset().top-150 }, 600);
}

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

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