javascript 如何使用html的onclick分配变量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8772077/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 04:31:12  来源:igfitidea点击:

How to assign a variable using onclick of html?

javascriptjqueryhtml

提问by user992654

I am writing a code where the onclick of html should cause a javascript variable to be assigned a value which causes a function to trigger.

我正在编写一个代码,其中 html 的 onclick 应该导致 javascript 变量被分配一个值,从而导致函数触发。

<script type="text/javascript">
function set_str(numb)
 {
   if(numb == 1)
   var str_in_func = 'a.tab_1';
   else if(numb == 2)
      var str_in_func = 'a.tab_2';
   return str_in_func;
}
jQuery(window).bind("load", function() {
str = set_str(num);

// When a link is clicked
$(str).click(function () {


// switch all tabs off
$(".active").removeClass("active");

// switch this tab on
$(this).addClass("active");

// slide all content up
$(".content").slideUp();

// slide this content up
var content_show = $(this).attr("title");
$("#"+content_show).slideDown();

});

});
</script>

I want the javascript variable str to have a value of 'a.tab_1' when the link below is clicked

当单击下面的链接时,我希望 javascript 变量 str 的值为 'a.tab_1'

<a href="#" title="content_1" onclick="var num = 1; return false;" class="tab_1 active" id="ma_link">Topics</a>

This doesn't seem to work though. The above jQuery function doesn't run at all.

但这似乎不起作用。上面的 jQuery 函数根本没有运行。

回答by Ansel Santosa

There is a much easier approach to this that doesn't require all the mucking about with HTML attributes:

有一个更简单的方法,不需要所有的 HTML 属性:

HTML:

HTML:

<nav>
    <a href="javascript:;" class="tab">tab 1</a>
    <a href="javascript:;" class="tab">tab 2</a>
</nav>
<div id="content">
    <section>Content 1</section>
    <section>Content 2</section>
</div>

JS

JS

$(document).ready(function() {
    $('.tab').on('click', function() {
        $('.active').removeClass('active');
        $(this).addClass("active");
        $('#content section')
            .slideUp()
            .eq($(this).index()).slideDown()
        ;
    });
});

See demonstration here.

请参阅此处的演示。

回答by benastan

<a href="#" title="content_1" onclick="var num = 1; return false;" class="tab_1 active" id="ma_link">Topics</a>

The problem is the varbefore your variable's name. Remove it and you will be fine. vartells javascript that you are declaring a variable for the local scope, not the context of the window, making it unavailable outside of the current context.

问题在于var变量名称之前。删除它,你会没事的。var告诉 javascript 您正在为局部范围声明一个变量,而不是窗口的上下文,使其在当前上下文之外不可用。

You want:

你要:

<a href="#" title="content_1" onclick="num = 1; return false;" class="tab_1 active" id="ma_link">Topics</a>