标签: Javascript

  • JQuery 如何获取select选中的值 图文教程

    JQuery 如何获取select选中的值 图文教程

    html代码

    <select id="ddl">
    <option value="100" emoney="12" >选项1</option>
    <option value="200" emoney="13" >选项2</option>
    <option value="300" emoney="14" >选项3</option>
    </select>

    Javascript代码部分

    //获取属性emoney的值
    var iteValue = $("#ddl").find("option:selected").attr("emoney");
    console.log('emoney的值:' + iteValue);
    //获取选中项的value
    var itemValue1 = $("#ddl").val();
    console.log('Value:' + itemValue1);
    //获取选中项的文本值
    var itemText = $("#ddl option:selected").text();
    console.log('Text:' + itemText);
    //获取选中项的文本值
    var itemText1 = $("#ddl").find("option:selected").text();
    console.log('Text:' + itemText1);

  • Javascript 计算两时间差换算天时分秒

    Javascript 计算两时间差换算天时分秒

    前面我们记录了 使用WdatePicker日期组件时,选择日期后,执行某个方法 。下面我们记录一下如何计算2个时间差,写成天小时分的格式

    function time_different( date1 , date2 ){
        var date3 = new Date(date2).getTime() - new Date(date1).getTime();   //时间差的毫秒数      
        //------------------------------
        //计算出相差天数
        var days=Math.floor(date3/(24*3600*1000))
        //计算出小时数
        var leave1=date3%(24*3600*1000)    //计算天数后剩余的毫秒数
        var hours=Math.floor(leave1/(3600*1000))
        //计算相差分钟数
        var leave2=leave1%(3600*1000)        //计算小时数后剩余的毫秒数
        var minutes=Math.floor(leave2/(60*1000))
        //计算相差秒数
        var leave3=leave2%(60*1000)      //计算分钟数后剩余的毫秒数
        var seconds=Math.round(leave3/1000)
        return days+" 天 "+hours+" 小时 "+minutes+" 分钟 "+seconds+" 秒";
    }

    调用方法:

        $("#begin_time").click(function(){
           WdatePicker({readOnly:true,dateFmt:'yyyy-MM-dd H:m'});
        });
        $("#end_time").click(function(){
            WdatePicker({readOnly:true,dateFmt:'yyyy-MM-dd H:m',onpicked:function(){
                var date2 = $('#end_time').val();
                var date1 = $('#begin_time').val();
                $('.duration').html( time_different(date1,date2) );
            }});
        });
  • 使用WdatePicker日期组件时,选择日期后,执行某个方法

    使用WdatePicker日期组件时,选择日期后,执行某个方法

        $("#end_time").click(function(){
            WdatePicker({readOnly:true,dateFmt:'yyyy-MM-dd H:m:s',onpicked:function(){
                    alert(123);
            }});
        });    

    1、onpicked:选择日期后执行的方法。

    2、dateFmt:显示日期的格式。

    3、maxDate:日期组件能选择和输入的最大日期,该格式默认为系统当前日期为最大日期。

    还有很多参数和样式,可以参照日期组件网站。

  • jquery 获取下拉列表select中选中值和选中项指定属性的解决办法

    jquery 获取下拉列表select中选中值和选中项指定属性的解决办法

    我们在javascript中,如果有监听change事件,无法直接获取到对应option的指定属性,我们需要使用如下写法才行:

    var strValue=$("#select_id").val(); //获取Select选择的Value
    var strText=$("#select_id").find("option:selected").text();   //获取Select选择的text
    var strText=$("#select_id").find("option:selected").attr('指定属性');   //获取Select选择的指定属性值
  • jQuery插件 — Cookie插件jquery.cookie.js 使用实例

    jQuery插件 — Cookie插件jquery.cookie.js 使用实例

    Cookie是网站设计者放置在客户端的小文本文件。Cookie能为用户提供很多的使得,例如购物网站存储用户曾经浏览过的产品列表,或者门户网站记住用户喜欢选择浏览哪类新闻。 在用户允许的情况下,还可以存储用户的登录信息,使得用户在访问网站时不必每次都键入这些信息

    使用方法:

    引入jquery.cookie.js

    <script src="scripts/jquery-1.6.4.js" type="text/javascript"></script>  
    <script src="scripts/jquery.cookie.js" type="text/javascript"></script>

    使用方法

    新添加一个会话 cookie

    $.cookie('the_cookie', 'the_value');

    注:当没有指明 cookie有效时间时,所创建的cookie有效期默认到用户关闭浏览器为止,所以被称为

    “会话cookie(session cookie)”。

    创建一个cookie并设置有效时间为 7天:

    $.cookie('the_cookie', 'the_value', { expires: 7 });

    注:当指明了cookie有效时间时,所创建的cookie被称为“持久 cookie (persistent  cookie)”。 

    创建一个cookie并设置 cookie的有效路径:

    $.cookie('the_cookie', 'the_value', { expires: 7, path: '/' });

    注:在默认情况下,只有设置 cookie的网页才能读取该 cookie。如果想让一个页面读取另一个页面设置的cookie,必须设置cookie的路径。cookie的路径用于设置能够读取 cookie的顶级目录。将这个路径设置为网站的根目录,可以让所有网页都能互相读取 cookie (一般不要这样设置,防止出现冲突) 。 

    读取cookie:

    $.cookie('the_cookie'); // cookie存在 => 'the_value'
    $.cookie('not_existing'); // cookie不存在 => null

    删除cookie,通过传递null作为cookie的值即可:

    $.cookie('the_cookie', null);

    将cookie写入文件

    var COOKIE_NAME = 'username';  
        if( $.cookie(COOKIE_NAME) ){  
            $("#username").val(  $.cookie(COOKIE_NAME) );  
        }  
        $("#check").click(function(){  
            if(this.checked){  
                $.cookie(COOKIE_NAME, $("#username").val() , { path: '/', expires: 10, domain: 'jquery.com', secure: true });  
                //var date = new Date();  
                //date.setTime(date.getTime() + (3 * 24 * 60 * 60 * 1000)); //三天后的这个时候过期  
                //$.cookie(COOKIE_NAME, $("#username").val(), { path: '/', expires: date });  
            }else{  
                $.cookie(COOKIE_NAME, null, { path: '/' });  //删除cookie  
            }  
        });

    参数设置

    expires: (Number | Date)      有效期,可以设置一个整数作为有效期(单位:天),也可以设置一个日期对象作为Cookie的过期日期。如果指定日期为负数,那么此cookie将被删除;如果不设置或者设置为null,那么此cookie将被当作Session Cookie处理,并且在浏览器关闭后删除

    path:  (String)          Cookie的路径属性,默认是创建该cookie的页面路径

    domain: (String)     Cookie的域名属性,默认是创建该cookie的页面域名

    secure: (Boolean)  如果设为true,那么此cookie的传输会要求一个安全协议,例如HTTPS

    jquery.cookie.js

    /**
     * Cookie plugin
     *
     * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
     * Dual licensed under the MIT and GPL licenses:
     * http://www.opensource.org/licenses/mit-license.php
     * http://www.gnu.org/licenses/gpl.html
     *
     */
    /**
     * Create a cookie with the given name and value and other optional parameters.
     *
     * @example $.cookie('the_cookie', 'the_value');
     * @desc Set the value of a cookie.
     * @example $.cookie('the_cookie', 'the_value', {expires: 7, path: '/', domain: 'jquery.com', secure: true});
     * @desc Create a cookie with all available options.
     * @example $.cookie('the_cookie', 'the_value');
     * @desc Create a session cookie.
     * @example $.cookie('the_cookie', null);
     * @desc Delete a cookie by passing null as value.
     *
     * @param String name The name of the cookie.
     * @param String value The value of the cookie.
     * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
     * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
     *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
     *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
     *                             when the the browser exits.
     * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
     * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
     * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
     *                        require a secure protocol (like HTTPS).
     * @type undefined
     *
     * @name $.cookie
     * @cat Plugins/Cookie
     * @author Klaus Hartl/klaus.hartl@stilbuero.de
     */
    /**
     * Get the value of a cookie with the given name.
     *
     * @example $.cookie('the_cookie');
     * @desc Get the value of a cookie.
     *
     * @param String name The name of the cookie.
     * @return The value of the cookie.
     * @type String
     *
     * @name $.cookie
     * @cat Plugins/Cookie
     * @author Klaus Hartl/klaus.hartl@stilbuero.de
     */
    jQuery.cookie = function(name, value, options) {
        if (typeof value != 'undefined') { // name and value given, set cookie
            options = options || {};
            if (value === null) {
                value = '';
                options.expires = -1;
            }
            var expires = '';
            if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
                var date;
                if (typeof options.expires == 'number') {
                    date = new Date();
                    date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
                } else {
                    date = options.expires;
                }
                expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
            }
            var path = options.path ? '; path=' + options.path : '';
            var domain = options.domain ? '; domain=' + options.domain : '';
            var secure = options.secure ? '; secure' : '';
            document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
        } else { // only name given, get cookie
            var cookieValue = null;
            if (document.cookie && document.cookie != '') {
                var cookies = document.cookie.split(';');
                for (var i = 0; i < cookies.length; i++) {
                    var cookie = jQuery.trim(cookies[i]);
                    // Does this cookie string begin with the name we want?
                    if (cookie.substring(0, name.length + 1) == (name + '=')) {
                        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                        break;
                    }
                }
            }
            return cookieValue;
        }
    };
  • 在Python3 Django框架 模板中如何使用条件判断?

    在Python3 Django框架 模板中如何使用条件判断?

    老季在本篇记录一下在Django的开发中,如何在模板中使用if判断条件。

    views.py

    # view 文件
    def func(request):
        ...
        return render(request,"index.html",{
            'current_user':"alex",
            'user_list':['alex','eric',
            'user_dict':{'k1':'v1','k2':'v2'}]
        })

    .html 模板

    # html 文件
    <html>
        ....
    <body>
        <div>{{current_user}}</div>
        <a>{{ user_list.0}}</a>
        # 条件判断
        {% if age %}
            <a> 有年龄<a>
        {% else %}
            <a> 无年龄<a>
        {% endif %}
        # 嵌套条件判断
        {% if age %}
            <a> 有年龄<a>
        {% if age > 16 %}
            <a>老男人<a>
        {% else %}
            <a>小男孩<a>
        {% else %}
            <a> 无年龄<a>
        {% endif %}
        <body>
    </html>
  • JQuery 合并 table 相同数据的列 rowspan

    JQuery 合并 table 相同数据的列 rowspan

    在实际项目应用当中,可能需要合并 table 表格中相同数据的列来显示数据,当然也可以再显示数据时使用rowspan属性来实现合并,但是这样比较复杂。这边我们直接给出使用 jQuery 的函数方法:

    jQuery.fn.rowspan = function(colIdx=0) {
        return this.each(function() {
            var that;
            $('tr', this).each(function(row) {
                $('td:eq(' + colIdx + ')', this).filter(':visible').each(function(col) {
                    if (that != null && $(this).html() == $(that).html()) {
                        rowspan = $(that).attr("rowSpan");
                        if (rowspan == undefined) {
                            $(that).attr("rowSpan", 1);
                            rowspan = $(that).attr("rowSpan");
                        }
                        rowspan = Number(rowspan) + 1;
                        $(that).attr("rowSpan", rowspan);
                        $(this).hide();
                    } else {
                        that = this;
                    }
                });
            });
        });
    }
    $(function() {
        //要合并的列序号,后面数字是第几列
        $("#content_table").rowspan(0); 
        $("#content_table").rowspan(1);
    });
  • Django 后台开发 为某个模型添加额外Javascript引用

    Django 后台开发 为某个模型添加额外Javascript引用

    最近在学Python,正好在一个项目中使用到了Django。网上查了很多资料如何为一个模型额外引用Javascript,基本都说得很简单并没有说到哪个文件哪个位置说的很笼统,对于初学者来说并不是很了解。这里记录一下如何为某个表增删改查时增加额外的 Javascript 。

    在应用的 admin.py 中配置即可,目录结构如上图所示:

    class ComputerRoomAdmin(admin.ModelAdmin):
        list_display = ('id', 'name','type','weights')
        list_display_links = ('id','name')  
        ordering = ('-weights',)
        class Media:
            js = ('/static/computerroom.js',)
    admin.site.register(models.ComputerRoom , ComputerRoomAdmin)

    这里的 js 即为需要使用的 Javascript 。

  • jQuery获取DropDownList下拉框操作Javascript代码实例 代码总结

    jQuery获取DropDownList下拉框操作Javascript代码实例 代码总结

    HTML

    <selected id="sel">
        <option value="1" selected="selected">a</option>
        <option value="2">b</option>
        <option value="3">c</option>
        <option value="4">d</option>
    </selected>

    获取选中项

    获取选中项的Value值:

    $('select#sel option:selected').val();

    或者

    $('select#sel').find('option:selected').val();

    获取选中项的Text值:

    $('select#seloption:selected').text();

    或者

    $('select#sel').find('option:selected').text();

    获取当前选中项的索引值

    $('select#sel').get(0).selectedIndex;

    获取当前option的最大索引值

    $('select#sel option:last').attr("index")

    获取DropdownList下拉框的长度

    $('select#sel')[0].options.length;

    或者

    $('select#sel').get(0).options.length;

    设置第一个option为选中值

    $('select#sel option:first').attr('selected','true')

    或者

     $('select#sel')[0].selectedIndex = 0;
  • jQuery操作radio单选框Javascript代码实例 图文教程

    jQuery操作radio单选框Javascript代码实例 图文教程

    HTML代码

    <input type="radio" name="rd" id="rd1" checked="checked" value="rd1" />
    <input type="radio" name="rd" id="rd2" value="rd2" />
    <input type="radio" name="rd" id="rd3" value="rd3" />

    获取选中值,三种方法都可以

    $('input:radio:checked').val();
    $("input[type='radio']:checked").val();
    $("input[name='rd']:checked").val();

    设置第一个Radio为选中值

    $('input:radio:first').attr('checked', 'checked');

    或者

    $('input:radio:first').attr('checked', 'true');

    注:attr(“checked”,’checked’)= attr(“checked”, ‘true’)= attr(“checked”, true)

    设置最后一个Radio为选中值

    $('input:radio:last').attr('checked', 'checked');
    

    或者

    $('input:radio:last').attr('checked', 'true');

    根据索引值设置任意一个radio为选中值

    $('input:radio').eq(索引值).attr('checked', 'true');索引值=0,1,2....

    或者

    $('input:radio').slice(1,2).attr('checked', 'true');

    根据Value值设置Radio为选中值

    $("input:radio[value=//www.jiloc.com']").attr('checked','true');

    或者

    
    $("input[value=//www.jiloc.com]").attr('checked','true');

    删除Value值为rd2的Radio

    $("input:radio[value=//www.jiloc.com]").remove();

    删除第几个Radio

    $("input:radio").eq(索引值).remove();索引值=0,1,2....
    如删除第3个Radio:$("input:radio").eq(2).remove();

    遍历Radio

    $('input:radio').each(function(index,domEle){
    //写入代码
    });
  • Vue.js 如何设置Select Option下拉值

    Vue.js 如何设置Select Option下拉值

    最近我们学习了解一下vue.js的基础内容,在Form表单中如何设定Select下拉框默认选中某个值。下面直接给出示范代码,这个示例还是比较容易理解的。

    HTML部分

    <script src="https://unpkg.com/vue@2.4.2"></script>
    <div class="form-group">
      <label class="control-label" for="docType">Type of document</label>
      <select class="form-control" id='docType' name="docType" v-model="docType" :disabled="noDocChoose == true">
                        <option value="paragon">Document1</option>
                        <option value="complaint">Document2</option>
                    </select>
    </div>

    JAVASCRIPT部分

    <script type="text/javascript">
    new Vue({
      el: ".form-group",
      data(){
        return {
          docType: "paragon"
        }
      }
    })
    </script>

    示例中,下拉 paragon 值就会被直接选中了。

  • Javascript开发jQuery Ajax 返回值如何阻止form表单提交?

    Javascript开发jQuery Ajax 返回值如何阻止form表单提交?

    在实际的开发业务中,我们一般会利用ajax检测一些东西,然后阻止表单提交。如果我们在 ajax 代码中直接使用 return false; 这里必须在 $.ajax 中设置 async:false 任然无法阻止表单提交,所以我们使用 the_submit 来控制表单是否提交。

    JAVASCRIPT代码部分

    <script type="text/javascript">
    $(function() {
        $("#addForm input.btn_submit").click(function(){
            var the_submit = true;
            if( $("input.name").val() == "" ){
                alert('请填写机房');
                $("input.name").focus();
                the_submit = false;
            }
            if( $("select.status").val() == "" ){
                alert('请选择状态');
                $("select.status").focus();
                the_submit = false;
            }
    	$.ajax({
                url:"/idc_xiaoshou/check_third_party_computer_room_name",
                dataType:"html",
                type:"post",
                data:{ name:$('input.name').val() },
                async:false,////////////
                success:function(data){
                  console.log(data);
                    if( data == 0 ){
                        alert("机房名重复");
                        $("input.name").focus();
                        the_submit = false;
                    }
                },
                error:function(data){
                    alert('UNKNOW ERROR');
                    the_submit = false;
                }
    	});
            if( !the_submit ){
                return false;
            }
        });
    
    });	
    </script>

    HTML代码部分

                <form enctype="multipart/form-data" action="/idc_xiaoshou/save_third_party_computer_room" method="post" id="addForm" name="form1" >     
                  <input type="hidden" name="id" value="<?php echo $obj['id']; ?>"/>
                  <table border="0" cellpadding="0" cellspacing="0" class="table2" style="margin:0 auto">          
                      <tr>
                          <td align="right">机房:</td>
                          <td><input class="textinput1 name" value="<?php echo $obj['name'];?>" type="text" name="name" style="width: 200px;"/></td>
                          <td><span class="color1">*</span></td>
                      </tr>
                      <tr>
                          <td align="right">状态:</td>
                          <td>
                              <select style="min-width: 100px" name="status" class="textinput1 status">
                                  <option value="" >所有</option>
                                  <?php foreach( $statusAry as $v):?>
                                  <option value="<?php echo $v;?>"><?php echo $v;?></option>
                                  <?php endforeach;?>
                              </select>        
                          </td>
                          <td><span class="color1">*</span></td>
                      </tr>
                      <tr>
                          <td align="right">备注:</td>
                          <td><textarea name="others" class="textinput1" cols="50" rows="10"><?php echo $obj['others']?></textarea></td>
                          <td></td>
                      </tr>        
                      <tr>
                          <td></td>
                          <td colspan="2"><input type="submit" value="提交" class="btn_submit"/></td>
                      </tr>
                </table>
                </form> 
WeChat
↑