Javascript 如何写一个简单的函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11042377/
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-08-24 04:11:49  来源:igfitidea点击:

How to write a simple function?

javascriptjquery

提问by user785179

How do you create a function in jQuery, call it, and pass a variable to it? Here it is in Javascript style:

你如何在 jQuery 中创建一个函数,调用它,并将一个变量传递给它?这是 Javascript 风格:

<script type="text/javascript">
function popup(msg) {
  alert(msg);
}
</script>

Then you would simply include the event in the HTML:

然后您只需将事件包含在 HTML 中:

<html>
<input type="submit" onclick="popup('My Message')" />
</html>

What is the jQuery equivalent to doing this? From all the "newbie" tutorials, they are all static functions that do not accept variables. For example:

什么是 jQuery 等价于这样做?从所有的“新手”教程来看,都是不接受变量的静态函数。例如:

<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
  $('button').click(function() {
    alert('hello, world');
   });
});
</script>

I want to be able to dynamically include different messages. The code above affects all buttons and spits out the same message of 'hello, world'.

我希望能够动态包含不同的消息。上面的代码影响所有按钮并输出相同的消息“你好,世界”。

回答by nzifnab

If you want the message to be dynamic, you're going to want to use data-attributes:

如果您希望消息是动态的,您将需要使用data-attributes

<input class='message-button-' type="submit" data-message="My Message" />

Then in a separate javascript file:

然后在一个单独的 javascript 文件中:

// equivalent of $(document).ready(function(){...
$(function(){

  // Functionality starts here
  $('.message-button').on('click', function(e){
    alert($(this).data('message'));
  })


});

Now the function will execute any time a button with class .message-buttonis clicked, and it will use the custom attribute data-message to display a message.

现在该函数将在任何时候单击具有类的按钮时执行.message-button,并且它将使用自定义属性 data-message 来显示消息。

Hope this helps! :)

希望这可以帮助!:)

Update:

更新:

Note that it's considered best-practice to do javascript unobstrusively. Some people have mentioned still using the onclickattribute like you did in your example, don't do that. Bind the event like I've shown here using jquery's .on('click', function(){})method.

请注意,不引人注意地执行 javascript 被认为是最佳实践。有些人提到仍然onclick像您在示例中那样使用该属性,不要那样做。使用 jquery 的.on('click', function(){})方法绑定我在此处显示的事件。

If your click item is an anchor tag <a>then you can prevent the href from being followed if you want, by using e.preventDefault:

如果您的点击项目是一个锚标签,<a>那么您可以根据需要阻止 href 被跟踪,方法是使用e.preventDefault

$('a').on('click', function(e){
  e.preventDefault()
})

Also in case you need to know, the $('.message-button')is using css selectors to grab dom elements. Any valid CSS selector will normally work in there.

另外,如果您需要知道,$('.message-button')使用 css 选择器来获取 dom 元素。任何有效的 CSS 选择器通常都可以在那里工作。

Step-by-step

一步步

First, we need to wrap all of our code in a function provided by jQuery that waits until the document is ready to handle javascript actions and dom manipulation. The long-form version is $(document).ready(function(){ /* CODE GOES HERE */ })but the version I've used is a shortcut $(function({ /* CODE GOES HERE */ }):

首先,我们需要将所有代码包装在 jQuery 提供的函数中,该函数会等待文档准备好处理 javascript 操作和 dom 操作。长版是$(document).ready(function(){ /* CODE GOES HERE */ })但我使用的版本是一个快捷方式$(function({ /* CODE GOES HERE */ })

$(function(){
})

Next, we need to bind an event to our button. Since we've given it the class .message-button, we can use jQuery to grab that element and bind the 'click' event to it:

接下来,我们需要将一个事件绑定到我们的按钮。因为我们已经给了它 class .message-button,所以我们可以使用 jQuery 来获取该元素并将 'click' 事件绑定到它:

$(function(){
  // Functionality starts here
  $('.message-button').on('click', function(e){
    // Code here executes when the input button is clicked
  })


});

Inside of event handlers thisis re-bound to point directly to the HTML element that triggered the event. Wrapping in $() gives us access to jquery methods. Thus: $(this) is used very frequently. jQuery gives us the .data()method to access any data-*methods on the element and give us the value, which is what the alert()is doing.

事件处理程序内部this被重新绑定以直接指向触发事件的 HTML 元素。包装在 $() 中使我们可以访问 jquery 方法。因此: $(this) 使用非常频繁。jQuery 为我们提供了.data()访问data-*元素上任何方法的方法,并为我们提供了值,这就是alert()正在做的事情。

$(function(){
  // Functionality starts here
  $('.message-button').on('click', function(e){
    alert($(this).data('message'));
  })


});

回答by Entaah Laah

This is my best way to do this just like javascript:

这是我最好的方法,就像 javascript 一样:

---- Make function by using jQuery like this

---- 像这样使用 jQuery 创建函数

<script>$(document).ready(function(){
    popup=function(msg){
      alert(msg);
    }});
</script>
<script>$(document).ready(function(){
    popup=function(msg){
      alert(msg);
    }});
</script>

And you don't need to change the code at the body

并且您不需要更改正文处的代码

<html>
<input type="submit" onclick="popup('My Message')" />
</html>
<html>
<input type="submit" onclick="popup('My Message')" />
</html>

Here is the sample http://jsfiddle.net/PLnF3/

这是示例http://jsfiddle.net/PLnF3/

---- But wait, If you just need to show an alert message maybe this sample is the best:

---- 但是等等,如果您只需要显示警报消息,也许这个示例是最好的:

<html>
<input type="submit" onclick="alert('My Message')" />
</html>
<html>
<input type="submit" onclick="alert('My Message')" />
</html>

You don't need any javascript or jQuery to do this, just use alert('My Message') on your button. Sample http://jsfiddle.net/PLnF3/1/

您不需要任何 javascript 或 jQuery 来执行此操作,只需在您的按钮上使用 alert('My Message') 即可。示例http://jsfiddle.net/PLnF3/1/

---- If you want a better appearance using jQuery, you can use jQuery Dialog().

---- 如果你想使用 jQuery 获得更好的外观,你可以使用 jQuery Dialog()。

Here the example http://howto.software-mirrors.com/2013/09/how-to-make-jquery-popup-window.htmlThis is the code:

这里的例子http://howto.software-mirrors.com/2013/09/how-to-make-jquery-popup-window.html这是代码:

<script>
    $(document).ready(function() {
        popup = function(msg) {
            $("<div>" + msg + "</div>").dialog();
        }
    });
</script>
<script>
    $(document).ready(function() {
        popup = function(msg) {
            $("<div>" + msg + "</div>").dialog();
        }
    });
</script>

And you don't need to change the html code on your body.

而且您不需要更改您身体上的 html 代码。

<html>
<input type="submit" onclick="popup('My Message')" />
</html>
<html>
<input type="submit" onclick="popup('My Message')" />
</html>

Here the example http://jsfiddle.net/PLnF3/2/

这里的例子http://jsfiddle.net/PLnF3/2/

Remember, to be able to use jQuery dialog, you need jquery.js, jquery-ui.js and also jquery.css theme. read more at http://howto.software-mirrors.com/2013/09/how-to-make-jquery-popup-window.html

请记住,为了能够使用 jQuery 对话框,您需要 jquery.js、jquery-ui.js 和 jquery.css 主题。在http://howto.software-mirrors.com/2013/09/how-to-make-jquery-popup-window.html阅读更多信息

回答by Ry-

You'd give each button a different ID, like so:

您可以为每个按钮指定不同的 ID,如下所示:

<input type="submit" id="submit-something" onclick="popup('My Message')" />

Then:

然后:

$(document).ready(function() {
    $('#submit-something').click(function() {
        alert('My message');
    });
});

Also, if the task is very repetitive, you can use another function to create the function:

此外,如果任务非常重复,您可以使用另一个函数来创建该函数:

function messageHandler(message) {
    return function() {
        alert(message);
    };
}

$(document).ready(function() {
    $('#submit-something').click(messageHandler('My message'));
});

回答by SLaks

You should store the message in a data-*attribute:

您应该将消息存储在data-*属性中:

<button data-message="Hi there!">...</button>
$('button').click(function() {
    alert($(this).data('message'));
});

回答by gdoron is supporting Monica

$(document).ready(function() {
    var message = "foo"; // You might need to move it to the global scope,
                         // denepends on what you want to do with it.
  $('button').click(function() {
    alert(message);
   });
   ...
   ...
   message = "hello world";
});

Worth saying sbout:

值得一说:

How do you create a function in jQuery

你如何在 jQuery 中创建一个函数

There is no such thing, create a function in jQuery.

没有这样的东西,在jQuery中创建一个函数。

回答by Niko

If you're absolutely required to store the data in the HTML code, the data attributes are a good choice:

如果您绝对需要在 HTML 代码中存储数据,那么 data 属性是一个不错的选择:

<button class="alert" data-msg="My Message">Click me</button>

JavaScript:

JavaScript:

$(document).ready(function() {
  $('button.alert').click(function() {
      var msg = $(this).data('msg');  // access HTML attribute data-msg
      alert(msg);
  });
});

回答by ivandcl

One solution:to use attributes like parameter.

一种解决方案:使用参数等属性。

<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
  $('button').click(function() {
    alert($(this).attr("message"));
   });
});
</script>
<button message="personal message 1">Botton 1</button>
<button message="personal message 1">Botton 2</button>

回答by edrose41

i've tried some of the suggestions and it works great..

我已经尝试了一些建议,效果很好..

--html button

--html 按钮

<input type="submit" value="Submit 1" class="message" data-message="Sample Message 1"/>
<input type="submit" value="Submit 2" class="message" data-message="Sample Message 2"/>

--jquery on button click

--jquery 按钮点击

$('.message').live('click', function(){
      alert($(this).data('message'));
});

回答by indranatha madugalle

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>POS</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script>


function getUnitPrice(){
        var item = document.getElementById('item').value;
        if(item==0){
            document.getElementById('unitprice').value = "36000.00";
        }
        if(item==1){
            document.getElementById('unitprice').value = "2500.00";
        }
        if(item==2){
            document.getElementById('unitprice').value = '14000.00';
        }
        if(item==3){
            document.getElementById('unitprice').value = '40000.00';
        }
        if (item==" "){
            document.getElementById('unitprice').value = '0';
        }


}

function calcSubtotal(){
    var qty = document.getElementById('quantity').value;
    var price = document.getElementById('unitprice').value;
    if(isNaN(qty)||isNaN(price)){
        alert("Please enter valid values");

    }
    else{
        var subtotal= eval(price) * eval(qty);
        document.getElementById('subtotal').value = subtotal;
    }




}


function calcDiscount(){

    var discRate = document.getElementById('discountRate').value;
    var discAmount = document.getElementById('subtotal').value;

    if(isNaN(discRate)||isNaN(discAmount)){
        alert("Please enter valid discount");
        return;
    }
    if(discRate < 5 || discRate > 20 ){
        alert("Please enter valid discount");
        return;
    }

    var discount = eval(discAmount) * eval(discRate)/100;
    document.getElementById('discountAmount').value = discount;
    document.getElementById('total').value= discAmount - discount;



}

function calcBalance(){

    var cash = document.getElementById('cash').value;
    var total = document.getElementById('total').value;

    if(isNaN(cash)){
        alert("Enter valid amount");
        return;
    }

    var bal = eval(total) - eval(cash);
    document.getElementById('balance').value = bal;



}

</script>

</head>

<body class="container">
    <div class="panel panel-primary" style="margin-top: 10px;">
        <div class="panel-heading">
            <p style="font-size: 36px; margin: 0;"><strong>Kumara Super Centre</strong></p>
            <p style="font-size: 16px; margin: 0;">No. 300, Ja-ela Road, Gampaha. Tel: 033-2232526</p>
        </div>
        <div class="panel-body">
        <table class="table table-hover">
            <tr>
                <th class="text-center">Item</th>
                <th class="text-center">Quantity</th>
                <th class="text-center">Unit Price</th>
                <th class="text-center">Amount</th>
            </tr>
            <tr>
                <td class="col-lg-5">
                    <select class="form-control" id="item" required onChange="getUnitPrice()">
                        <option value="">Select one</option>
                        <option value="0">Television</option>
                        <option value="1">FM Radio</option>
                        <option value="2">DVD Player</option>
                        <option value="3">Surround System</option>
                    </select>
                </td>
                <td class="col-lg-2">
                    <input class="form-control" type="number" value="0" id="quantity" name="quantity" required onKeyUp="calcSubtotal()" />
                </td>
                <td class="col-lg-2">
                    <input class="form-control" type="number" value="0" id="unitprice" name="unitprice" readonly />
                </td>
                <td class="col-lg-3">
                    <input class="form-control" type="number" value="0" id="subtotal" name="subtotal" readonly />
                </td>
            </tr>
        </table>
        <table class="table" style="float: right; width: 600px;">
            <tr style="border:none">
                <td class="text-center col-lg-3"><strong>Discount Rate (%)</strong></td>
                <td class="col-lg-2"><input class="form-control" type="number" value="0" id="discountRate" name="discountRate" onKeyUp="calcDiscount()" /></td>
                <td class="col-lg-3"><input class="form-control" type="number" value="0" id="discountAmount" name="discountAmount" readonly /></td>
            </tr>
            <tr style="border-top:none">
                <td class="text-center"><strong>Total</strong></td>
                <td></td>
                <td><input class="form-control" type="number" value="0" id="total" name="total" readonly /></td>
            </tr>
            <tr style="border:none">
                <td class="text-center"><strong>Cash</strong></td>
                <td></td>
                <td><input class="form-control" type="number" value="0" id="cash" name="cash" onKeyUp="calcBalance()" /></td>
            </tr>
            <tr style="border:none">
                <td class="text-center"><strong>Balance</strong></td>
                <td></td>
                <td><input class="form-control" type="number" value="0" id="balance"  name="balance" readonly /></td>
            </tr>
        </table>

        </div>



    </div>
</body>
</html>