指定样式表的'title'属性不允许应用它?

时间:2013-03-12 20:06:31

标签: javascript jquery html css

我的代码有效:

$(document).ready(function () {

  var style = $('#formulario').val();

  $('#formulario').change(function() {
    var nombreArchivo = $(this).val();
    nombreArchivo = nombreArchivo.replace(/ /gi, '_');
    var ruta = '/printbox/views/formulariosweb/';
    $('#contenedorFormulario').load( ruta + nombreArchivo + '.html');
    $('head').append( $('<link rel="stylesheet" type="text/css"/>').attr('href', ruta + nombreArchivo + '.css') );
  });

  $("#formulario").trigger('change');

});

它根据表单中的选择更改div的内容,并且每次更改时都正确应用样式。

但是,当我更改表单中的值时,它会多次添加css。

当我尝试将title属性设置为LINK时出现问题,然后只有第一个样式有效,当我更改它时,新样式会加载到{{1}但是没有被应用。

我去了W3网站(http://www.w3schools.com/tags/tag_link.asp),它说LINK支持属性head,所以我不知道这里有什么问题。我这样添加:

title

非常感谢任何帮助。

由于

PS:我添加了title属性,以便稍后识别并删除它,一旦我更改了下拉列表中的值,所以它不会填充标题。

2 个答案:

答案 0 :(得分:1)

您可以使用以下方法检查是否尚未加载样式表:

if (!$("link[href='/path/to.css']").length)

因此,如果目标最终只是您想要加载每个样式表一次,那么您的代码将是:

$(document).ready(function () {

  var style = $('#formulario').val();

  $('#formulario').change(function() {
    var nombreArchivo = $(this).val();
    nombreArchivo = nombreArchivo.replace(/ /gi, '_');
    var ruta = '/printbox/views/formulariosweb/';
    $('#contenedorFormulario').load( ruta + nombreArchivo + '.html');
    if (!$("link[href='" + ruta + nombreArchivo + "'.css']").length) {
      $('head').append( $('<link rel="stylesheet" type="text/css"/>').attr('href', ruta + nombreArchivo + '.css') );
    }
 });

 $("#formulario").trigger('change');

});

答案 1 :(得分:1)

我去向Mozilla bugtrack报告了这个问题,发现了一个类似的问题(https://bugzilla.mozilla.org/show_bug.cgi?id=223410)讨论了这个问题,并引导我进入了这个页面:

http://www.w3.org/TR/html401/present/styles.html#h-14.3.1

其中规范说明指定title属性使其成为首选样式,然后不应用其他样式。

Authors may specify a number of mutually exclusive style sheets called alternate style sheets. Users may select their favorite among these depending on their preferences.
For instance, an author may specify one style sheet designed for small screens and another for users with weak vision (e.g., large fonts).
User agents should allow users to select from alternate style sheets.

The author may specify that one of the alternates is a preferred style sheet. User agents should apply the author's preferred style sheet unless the user has selected a different alternate.