简体   繁体   中英

Javascript Function To Change Div Style

I have a javascript script that gets the number of notifications from a php file and then displays the number into a div in the code.

<script>
//DISPLAY NUMBER OF UNREAD NOTIFICATIONS AND UPDATE EVERY 5 SECONDS
window.setInterval(function(){

   $("#notes_number").load("getnumber.php");

}, 5000);

//WHEN THE BUTTON IS PRESSED THIS HAPPENS
function toggleDiv(divId) {
   $("#"+divId).show();
//GET THE NOTIFICATIONS 
$(document).ready(function(){
   $("#myContent").load("getnotes.php?page=<? echo $page; ?>");
});

//RESET THE NUMBER OF UNREAD NOTIFICATIONS
$(document).ready(function(){
   $("#notes_number").load("getnumber.php");
});


}

</script>

<div id='notes_number'> </div>

The number is in a bell shaped icon and when the number goes above 9 it becomes off center. I'd like to have it set to <div id='notes_number' style='right: 30px;'></div> whenever the number gets above 9.

The issue I'm having is I have no idea how to get the number into a php variable so I can make the if else statement like so:

if ($thenumber <= "9") {
echo "<div id='notes_number'> </div>";
}
else {
echo "<div id='notes_number' style='right: 30px;'></div>";
}

CODE USED RECENTLY:

window.setInterval(function(){
    $("#notes_number").load("getnumber.php");

    var value = parseInt($('#notes_number').text());

    if(value > 9){
    $('#notes_number').css('right','30px');
    }
}, 5000);

在铃声里面的html总是只放<div id='notes_number'></div>然后你可以在你的javascript中加载数字并通过jquery添加样式(如果数字超过9)就像这样: $('#notes_number').css('right','30px');

This can be solved in the JavaScript layer. Instead of using .load , try using .get to inspect the value, and then assign styles accordingly.

window.setInterval(function(){

    $.get("getnumber.php", function(data) {

        $("#notes_number").val(parseInt(data,10));

        if(parseInt(data,10) > 9) {
            $("#notes_number").css('right','30px');
        } else {
            $("#notes_number").css('right','0');
        }

    });

}, 5000);

You can use the same mark-up so:

<div id='notes_number'> </div>

then in your jquery you can grab the value:

var value = parseInt($('#notes_number').text());

and add a class if it is over 9

if(value > 9){
    $('#notes_number').addClass('largeNumber');
}

and let the CSS take care of the style rather than using inline styles via JS:

.largeNumber{
    right: 30px;
}

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.

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