如果不存在,jquery附加文本

时间:2014-11-03 16:56:08

标签: jquery

如果文本中不存在文本,我试图附加文本,如果它存在则不附加:

<form method="post" action="" class="horizontal-form">
<fieldset>
<input type="file" align="left" name="patient_image[]" multiple="multiple" min="1" max="6"/>
</fieldset>
</form>
jQuery(function(){


$('form').each(function () {
    if ($(this).find('fieldset').html() ===  '<br/>Total image size is limited to 4MB.  If you are uploading more than one image, the total combined size is still 4MB.  Files should be formatted into JPG or BMP.') {
       $("input[name*='patient_image']").after('<br/>Total image size is limited to 4MB.  If you are uploading more than one image, the total combined size is still 4MB.  Files should be formatted into JPG or BMP.');
    }
});



});

这是我到目前为止尝试过的小提琴的链接:http://jsfiddle.net/zbpv5zfk/37/

2 个答案:

答案 0 :(得分:1)

&#13;
&#13;
jQuery(function() {
  var sText = 'Total image size is limited to 4MB.  If you are uploading more than one image, the total combined size is still 4MB.  Files should be formatted into JPG or BMP.';
  $('form').find('fieldset:not(:contains("' + sText + '"))')
  .find("input[name*='patient_image']").after( '<br/>' + sText);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" action="" class="horizontal-form">
  <fieldset>
    <input type="file" align="left" name="patient_image[]" multiple="multiple" min="1" max="6" />
  </fieldset>
</form>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

它永远不会发生,因为如果您转储到控制台:$(this).find('fieldset').html()它的值将是:

`

                    <input name="patient_image[]" multiple="multiple" min="1" max="6" align="left" type="file">
             [and a new line and a lot of space here]

所以,你需要做的是检查你的文本的一部分,是否存在,如果没有,则附加:

$(function() {
    if ($(this).find('fieldset').html().indexOf('Total image size is limited to 4MB') === -1) {
        $(this).find('fieldset').after('<br/>Total image size is limited to 4MB.  If you are uploading more than one image, the total combined size is still 4MB.  Files should be formatted into JPG or BMP.');
    }
});

参见jsfiddle:http://jsfiddle.net/zbpv5zfk/38/

当然你也可以使用整个字符串。但我认为,这是一种不好的做法,因为如果你想改变文本中的任何内容,那就很难维护。