问题描述:

I want to set a permanent value to a div element with jQuery;

the full js file:

$(function () {

var $a;

var $b;

$('button').click(function () {

$a = $('#a').val();

$b = $('#b').val();

var $big = getBigger($b, $a);

var $small = getSmaller($b, $a);

$('#bigger').text($big);

$('#smaller').text($small);

});

});

//a simple function for getting a bigger element

function getBigger(a, b) {

return a ^ (a ^ b) & -(a < b);

}

//a simple function for getting a smaller element

function getSmaller(a, b) {

return (a < b) ? a : b;

}

the full html file:

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta charset="utf-8" />

<link rel="stylesheet" type="text/css" href="style/style.css">

<title>Compare</title>

</head>

<body>

<form>

Enter a: <input type="number" id="a"><br/>

Enter b: <input type="number" id="b"><br/>

<button> Compare</button>

<div id="bigger"></div>

<div id="smaller"> </div>

</form>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>

<script src="js/app.js"></script>

</body>

</html>

The problem is that when I leave the scope the variable gets destroyed

PS. Now I realise that my mistake is that when a <button> is added in a form element, everytime the button is pressed, the data in the form gets reseted

网友答案:

When you run code within a function it creates a scope. Each variable you define using the var statement will be available only in that scope.

To create a variable for usage outside of the current scope, either declare a variable without putting var beforehand or directly write window.varname = value. Have another read on that topic.

Besides that, in your code $('#bigger').text($big); the var $big never even gets defined, so maybe that is the problem.

And setting an elements text works independent from scopes or variables.

网友答案:

Try this

To Access:

$("#a").data('value');

To Set

$("#a").data('value' , 'whatevervalue');

To Access Without JQuery:

document.getElementById("a").dataset.value;

To Set Without JQuery;

document.getElementById("a").dataset.value = "Some Value";

A Div cannot hold the Value attribute unless you use:

document.getElementById("a").setAttribute("value" , "val");

Then to Assign it to Inside your div:

$("#myDivElement").html($("#a").data('value'))
相关阅读:
Top