I have a small script where I need one value to xor. Someone pointed out how to do it, but I have since changed the script and his suggestion doesn't apply here anymore.
<input type='button' value='Ein / Aus' class='taster' csv='Lampe' />
<script>
$(document).on('click', 'input.taster', function() {
// Get ID from Input
var id = $(this).attr('csv');
$.get('plc.php?function=csv&id=' + id, function(data){
var csv = data.split(',');
//Output
var out = csv[1];
//Write
var wdatatyp = csv[2];
var wdb = csv[3];
var wbyte = csv[4];
var wbit = csv[5];
var bitval = csv[6];
//Read
var rdatatyp = csv[7];
var rdb = csv[8];
var rbyte = csv[9];
var rbit = csv[10];
$(document).load('plc.php?function=write-bit', {'wdatatype':wdatatyp, 'wdb':wdb, 'wbyte':wbyte, 'wbit':wbit, 'bitval':bitval});
function read() {
$(out).load('plc.php?function=read-bit', {'rdatatype':rdatatyp, 'rdb':rdb, 'rbyte':rbyte, 'rbit':rbit});
}
setTimeout(read, 100);
});
});
</script>
A little cleanup and better description of what needs to happen.
csv[6] is fetched from the csv file and will always return 1.
So what I need is the first time the script is called, bitval needs to return a 1. The next time it needs to return a 0, then a 1, then a 0, etc.
You need to convert the bitval
to an int
before XORing it. So replace the line
var bitval = csv[6];
with
var bitval = parseInt(csv[6]);
The toggling can be then done this way (by moving the bitval declaration out of the onClick handler):
var bitval = null; // this is crucial since you don't have another place to store the value
$(document).on('click', 'input.taster', function() {
var id = $(this).attr('csv');
$.get('plc.php?function=csv&id=' + id, function(data){
// your variables
if (bitval == null) { // initial set
bitval = parseInt(csv[6]); // was 'var bitval = csv[6]'
}
// your load code
bitval ^= 1; // toggle
});
});
As Artjom mentioned, you need to convert it to a number since .split()
returns strings.
var bitval = Number(csv[6]);
You can do the XOR ing in the same step:
var bitval = Number(csv[6]) ^ 1;
In the case that the value cannot be converted to a number, the Number function will return NaN
(not-a-number). NaN ^ 1
equals 1. If that result is undesirable, you can do a type check:
var bitval = Number(csv[6]);
if (isNaN(bitval)) {
bitval = ...;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.